%\vfill\eject
\chapter{基本库（Base library）}
\label{baselibrarychapter}

本章描述Scheme的\defrsixlibrary{base}库，其导出了很多通常和Scheme一起的过程和语法绑定。

第\ref{basetailcontextsection}小节定义了来自\rsixlibrary{base}库的从结构上识别尾调用和尾上下文的规则。

\section{基本类型（Base types）}
\label{disjointness}

没有变量满足下列谓词中的多个：

\begin{scheme}
boolean?          pair?
symbol?           number?
char?             string?
vector?           procedure?
null?%
\end{scheme}

这些谓词定义了基本的类型{\em 布尔}，{\em 点对}，{\em 符号}，{\em 数字}，{\em 字符}，{\em 字符串}，{\em 向量}，以及{\em 过程}。此外，空表是一个特殊的对象，它有自己的类型。
\mainindex{type，类型}\schindex{boolean?}\schindex{pair?}\schindex{symbol?}
\schindex{number?}\schindex{char?}\schindex{string?}\schindex{vector?}
\schindex{procedure?}\index{empty list，空表}\schindex{null?}

注意，尽管有一个单独的布尔类型，但是，任何Scheme值在条件测试中都可以被当作一个布尔值使用；见\ref{booleanvaluessection}小节。

\section{定义（Definitions）}
\label{defines}

定义\mainindex{definition，定义}出现在一个\meta{top-level body}（\ref{programsyntaxsection}小节）中，\meta{library body}的最上面（\ref{librarysyntaxsection}小节），或\meta{body}的最上面（\ref{bodiessection}小节）。

一个\hyper{definition}可以是一个变量定义（\ref{variabledefinitionsection}小节），或一个关键词定义（\ref{variabledefinitionsection}小节）。扩展到定义或定义组（打包在一个{\cf begin}, {\cf let-syntax}, 或{\cf letrec-syntax}形式中；见\ref{begin}小节）中的宏使用也可以出现在任何其它定义可以出现的地方。

\subsection{变量定义}
\label{variabledefinitionsection}

本节描述的{\cf define}形式是一个用作创建变量绑定的\hyper{definition}\mainindex{definition，定义}，且可以出现在其它定义可以出现的任何地方。


% TODO
\begin{entry}{%
\proto{define}{ \hyper{variable} \hyper{expression}}{\exprtype}
\rproto{define}{ \hyper{variable}}{\exprtype}
\pproto{(define (\hyper{variable} \hyper{formals}) \hyper{body})}{\exprtype}
\pproto{(define (\hyper{variable} .\ \hyper{formal}) \hyper{body})}{\exprtype}}


{\cf define}的第一个形式绑定\hyper{variable}到一个新的位置，然后将\hyper{expression}的值赋值给这个位置。
\begin{scheme}
(define add3
  (lambda (x) (+ x 3)))
(add3 3)                            \ev  6
(define first car)
(first '(1 2))                      \ev  1%
\end{scheme}
%
\hyper{expression}的继续不应该被调用多于一次。

% TODO
\implresp 实现应当检测\hyper{expression}的继续被调用多于一次的情况。如果实现检测到这个的话，它必须抛出一个条件类型是{\cf\&assertion}的异常。

{\cf define}的第二种形式等价于
\begin{scheme}
(define \hyper{variable} \hyper{unspecified})%
\end{scheme}
其中\hyper{unspecified}是一个返回未定义值得无副作用的表达式。

在{\cf define}的第三个形式中，\hyper{formals}必须或者是零个或多个变量的序列，或者是一个或多个变量的序列，其跟着一个点{\cf .}和另一个变量（就像在一个lambda表达式中一样，见\ref{lambda}小节）。这个形式等价于
\begin{scheme}
(define \hyper{variable}
  (lambda (\hyper{formals}) \hyper{body}))\rm.%
\end{scheme}

在{\cf define}的第四个形式中，\hyper{formal}必须是一个单独的变量。这个形式等价于
\begin{scheme}
(define \hyper{variable}
  (lambda \hyper{formal} \hyper{body}))\rm.%
\end{scheme}
\end{entry}

\subsection{语法定义（Syntax definitions）}
\label{syntaxdefinitionsection}

本节描述的{\cf define-syntax}形式是一个用作创建关键词绑定的\hyper{definition}\mainindex{definition，定义}，其可以出现在任何其它定义可以出现的地方。

\begin{entry}{%
\proto{define-syntax}{ \hyper{keyword} \hyper{expression}}{\exprtype}}

绑定\hyper{keyword}到\hyper{expression}的值，其必须在宏扩展的阶段求值得到一个转换器。宏转换器可以使用\ref{syntaxrulessection}小节描述的{\cf syntax-rules}和{\cf identifier-syntax}形式创建。见库的第\extref{lib:transformerssection}{Transformers}小节，那儿有一个转换器更全面的描述。

通过{\cf define-syntax}建立的关键词绑定在其出现的整个内部都是可见的，除非被其它绑定覆盖外都是可见的，就像{\cf define}建立的变量绑定一样。通过一组定义建立的绑定，不管是关键词还是变量定义，在定义它们自己中是可见的。

\implresp 实现应该检测\hyper{expression}的值是不是一个适当的转换器。

例子：

\begin{scheme}
(let ()
  (define even?
    (lambda (x)
      (or (= x 0) (odd? (- x 1)))))
  (define-syntax odd?
    (syntax-rules ()
      ((odd?  x) (not (even? x)))))
  (even? 10))                       \ev \schtrue{}%
\end{scheme}

从左到右的处理顺序（第\ref{expansionchapter}章）的言外之意是一个定义可以影响后续的形式是否也是一个定义。

例子：

\begin{scheme}
(let ()
  (define-syntax bind-to-zero
    (syntax-rules ()
      ((bind-to-zero id) (define id 0))))
  (bind-to-zero x)
  x) \ev 0%
\end{scheme}

任何出现在{\cf let}表达式外面的{\cf bind-to-zero}的绑定都不会影响其行为。
\end{entry}

\section{内部（Bodies）}
\label{bodiessection}

\index{body，内部}\ide{lambda}, \ide{let}, \ide{let*}, \ide{let-values}, \ide{let*-values}, \ide{letrec}, 或\ide{letrec*}表达式的\hyper{body}，或由零个或多个跟着一个或多个表达式的定义。

{\cf \hyper{definition} \ldots{} \hyperi{expression} \hyperii{expression} \ldots}

通过一个定义定义的标识符在\hyper{body}中局部的。也就是说，标识符被绑定到，且绑定的作用域是这个\hyper{body}（见第\ref{variablesection}小节）。

例子
%
\begin{scheme}
(let ((x 5))
  (define foo (lambda (y) (bar x y)))
  (define bar (lambda (a b) (+ (* a b) a)))
  (foo (+ x 3)))                \ev  45%
\end{scheme}
%
当{\cf begin}, {\cf let-syntax}, 或{\cf letrec-syntax}形式先于第一个表达式出现在内部的时候，它们被拼接到内部；见第\ref{begin}小节。内部的一些或所以<!-- TODO -->，包括{\cf begin}, {\cf let-syntax}, 或{\cf letrec-syntax}形式里面的部分，可以通过一个宏使用指定（见第\ref{macrosection}小节）。

一个包含变量定义的被扩展的\hyper{body}（见第\ref{expansionchapter}章）总是可以被转换成一个等价的{\cf letrec*}表达式。比如，上面例子中的{\cf let}表达式等价于

\begin{scheme}
(let ((x 5))
  (letrec* ((foo (lambda (y) (bar x y)))
            (bar (lambda (a b) (+ (* a b) a))))
    (foo (+ x 3))))%
\end{scheme}

\section{表达式}
\label{expressionsection}

本节的条目描述\rsixlibrary{base}库中的表达式，除了第\ref{primitiveexpressionsection}小节描述的基本表达式类型，其可以出现在\hyper{expression}句法变量的位置中。

\subsection{引用（Quotation）}\unsection
\label{quotesection}

\begin{entry}{%
\proto{quote}{ \hyper{datum}}{\exprtype}}

\syntax \hyper{Datum}应该是一个句法数据。 % TODO

\semantics
{\cf (quote \hyper{datum})}的值是\hyper{datum}表示的数据值（见第\ref{datumsyntaxsection}小节）。这个符号被用作包含常量。 % TODO

\begin{scheme}%
(quote a)                     \ev  a
(quote \sharpsign(a b c))     \ev  \#(a b c)
(quote (+ 1 2))               \ev  (+ 1 2)%
\end{scheme}

正如第\ref{abbreviationsection}小节所说，{\cf (quote \hyper{datum})}可以使用缩写\singlequote\hyper{datum}：

\begin{scheme}
'"abc"               \ev  "abc"
'145932              \ev  145932
'a                   \ev  a
'\#(a b c)           \ev  \#(a b c)
'()                  \ev  ()
'(+ 1 2)             \ev  (+ 1 2)
'(quote a)           \ev  (quote a)
''a                  \ev  (quote a)%
\end{scheme}

正如第\ref{storagemodel}小节所说，常量是不可变得。

\begin{note}
  一个{\cf quote}表达式值的不同常数可以共享相同的位置。
\end{note}
\end{entry}

\subsection{过程}\unsection
\label{lamba}

\begin{entry}{%
\proto{lambda}{ \hyper{formals} \hyper{body}}{\exprtype}}

\syntax
\hyper{Formals}必须是一个下面描述的形参（formal parameter）列表，且\hyper{body}必须和第\ref{bodiessection}小节描述的一样。

\semantics
\vest \lambdaexp{}表达式的值是过程。当\lambdaexp{}表达式被求值时的有效环境被作为过程的一部分被记忆。当过程随后以一些参数被调用的时候，\lambdaexp{}表达式被求值时使用的环境通过绑定参数列表中的变量到新的位置的方式被扩展，且相应的实参值被存储到那些位置。然后，\lambdaexp{}表达式内部的表达式（其可能包含定义，因此可能表现为一个{\cf letrec*}形式，见第\ref{bodiessection}小节）在扩展的环境中被顺序地求值。内部最后一个表达式的结果作为过程调用的结果被返回。

\begin{scheme}
(lambda (x) (+ x x))      \ev  {\em{}一个过程}
((lambda (x) (+ x x)) 4)  \ev  8

((lambda (x)
   (define (p y)
     (+ y 1))
   (+ (p x) x))
 5) \ev 11

(define reverse-subtract
  (lambda (x y) (- y x)))
(reverse-subtract 7 10)         \ev  3

(define add4
  (let ((x 4))
    (lambda (y) (+ x y))))
(add4 6)                        \ev  10%
\end{scheme}

\hyper{Formals}必须有下列的形式之一：

\begin{itemize}
\item {\tt(\hyperi{variable} \dotsfoo)}:
过程拥有固定数量的参数。当过程被调用时，参数将被存储在相应变量的绑定中。

\item \hyper{variable}:
过程拥有任意数量的参数。当过程被调用时，实参的序列被转换为一个新创建的表，该表存储在\hyper{variable}的绑定中。

\item {\tt(\hyperi{variable} \dotsfoo{} \hyper{variable$_{n}$}\ {\bf.}\
\hyper{variable$_{n+1}$})}:
如果一个由空格分隔的{\cf .}出现在最后一个变量之前，该过程就拥有$n$个或更多个参数，这里的$n$是句点前面形参的个数（至少要有一个）。存储在最后一个参数绑定中的值是一个新创建的表。除了已和其他形参匹配的所有其他实参外，剩余的实参都被存入该表中。
\end{itemize}

\begin{scheme}
((lambda x x) 3 4 5 6)          \ev  (3 4 5 6)
((lambda (x y . z) z)
 3 4 5 6)                       \ev  (5 6)%
\end{scheme}

在\hyper{formals}中任何\hyper{variable}必须不能出现超过一次。
\end{entry}


\subsection{条件表达式（Conditionals）}\unsection

\begin{entry}{%
\proto{if}{ \hyper{test} \hyper{consequent} \hyper{alternate}}{\exprtype}
\rproto{if}{ \hyper{test} \hyper{consequent}}{\exprtype}}  %\/ if hyper = italic

\syntax
\hyper{Test}，\hyper{consequent}和\hyper{alternate}必须是表达式。

\semantics
{\cf if}表达式按如下方式计算：首先，计算\hyper{test}的值。如果产生一个真值\index{true，真值}（见第\ref{booleanvaluessection}小节），然后\hyper{consequent}被计算，且它的值被返回。否则，\hyper{alternate}被计算，且它的值被返回。如果\hyper{test}产生\schfalse{}且没有指定\hyper{alternate}，那么，表达式的结果是未定义的（\isunspecified）。

\begin{scheme}
(if (> 3 2) 'yes 'no)           \ev  yes
(if (> 2 3) 'yes 'no)           \ev  no
(if (> 3 2)
    (- 3 2)
    (+ 3 2))                    \ev  1
(if \#f \#f)                    \ev \theunspecified%
\end{scheme}

\hyper{consequent}和\hyper{alternate}表达式在尾上下文中，如果{\cf if}表达式它自己在的话；见第\ref{basetailcontextsection}小节。
\end{entry}


\subsection{赋值（Assignments）}\unsection
\label{assignment}

\begin{entry}{%
\proto{set!}{ \hyper{variable} \hyper{expression}}{\exprtype}}

\hyper{Expression}被计算，且结果值被存进\hyper{variable}绑定的位置。\hyper{Variable}必须在包含{\cf set!}表达式的区域或顶层被绑定。{\cf set!}表达式的结果是未定义的。

\begin{scheme}
(let ((x 2))
  (+ x 1)
  (set! x 4)
  (+ x 1)) \ev  5%
\end{scheme}

如果\hyper{variable}引用一个不可修改的绑定，那么这时一个语法错误。

\begin{note}
  标识符{\cf set!}同时以级别$1$被导出。见第\ref{identifier-syntax}小节。
\end{note}
\end{entry}

\subsection{派生（Derived）条件表达式}\unsection

\begin{entry}{%
\proto{cond}{ \hyperi{cond clause} \hyperii{cond clause} \dotsfoo}{\exprtype}
\litproto{=>}
\litproto{else}}

\syntax
每一个\hyper{cond clause}必须是形式
\begin{scheme}
(\hyper{test} \hyperi{expression} \dotsfoo)%
\end{scheme}
其中\hyper{test}是一个表达式。或有另一种选择，一个\hyper{cond clause}可以是形式\begin{scheme}
(\hyper{test} => \hyper{expression})%
\end{scheme}
最后一个\hyper{cond clause}可以是一个“{\cf else}子句”，其有形式
\begin{scheme}
(else \hyperi{expression} \hyperii{expression} \dotsfoo)\rm。%
\end{scheme}

\semantics
一个{\cf cond}表达式通过以下方式求值，按顺序连续地对\hyper{test}表达式进行求值直到它们其中一个的值是真值（见第\ref{booleanvaluessection}小节）。当一个\hyper{test}的值是真值的时候，就会顺序地对它\hyper{cond clause}中剩余的\hyper{expression}进行求值，且\hyper{cond clause}中最后一个\hyper{expression}的结果会作为整个{\cf cond}表达式的结果被返回。如果被选择的\hyper{cond clause}只包含\hyper{test}且没有\hyper{expression}，那么\hyper{test}的值会作为结果被返回。如果被选择的\hyper{cond clause}使用\ide{=>}辅助形式，那么\hyper{expression}被计算。它的值必须是一个过程。这个过程必须接受一个参数；它被以\hyper{test}的值调用，且过程返回的值作为{\cf cond}表达式的值返回。如果所有的\hyper{test}的值都是\schfalse，并且没有{\cf else}子句，那么条件表达式返回未定义的值（\unspecifiedreturn）；如果有一个{\cf else}子句，那么它的\hyper{expression}被计算，且最后一个的值被返回。

\begin{scheme}
(cond ((> 3 2) 'greater)
      ((< 3 2) 'less))         \ev  greater%

(cond ((> 3 3) 'greater)
      ((< 3 3) 'less)
      (else 'equal))            \ev  equal%

(cond ('(1 2 3) => cadr)
      (else \schfalse{}))         \ev  2%
\end{scheme}

对于一个有下列的形式之一的\hyper{cond clause}
%
\begin{scheme}
(\hyper{test} \hyperi{expression} \dotsfoo)
(else \hyperi{expression} \hyperii{expression} \dotsfoo)%
\end{scheme}
%
最后一个\hyper{expression}在尾上下文中，如果{\cf cond}形式它自己在的话。一个如下形式的\hyper{cond clause}
\begin{scheme}
(\hyper{test} => \hyper{expression})%
\end{scheme}

来自\hyper{expression}求值结果的过程的（隐式）调用在尾上下文中如果{\cf cond}形式它自己在的话。见第\ref{basetailcontextsection}小节。

一个更简单形式的{\cf cond}的参考定义可以在附录\ref{derivedformsappendix}中被找到。
\end{entry}


\begin{entry}{%
\proto{case}{ \hyper{key} \hyperi{case clause} \hyperii{case clause} \dotsfoo}{\exprtype}}

\syntax
\hyper{Key}必须是一个表达式。每一个\hyper{case clause}必须有下列形式之一：
\begin{scheme}
((\hyperi{datum} \dotsfoo) \hyperi{expression} \hyperii{expression} \dotsfoo)
(else \hyperi{expression} \hyperii{expression} \dotsfoo)%
\end{scheme}
\schindex{else}
第二个形式，其指定一个“{\cf else}子句”，只可以作为最后一个\hyper{case clause}出现。每一个\hyper{datum}是一些对象的一个外部表示。\hyper{Datum}表示的数据不需要有区别。

\semantics
一个{\cf case}按如下求值。\hyper{key}被求值，且它的结果被和每个\hyper{case clause}中的\hyper{datum}表示的数据轮流比较，比较的依据是{\cf eqv?}（见第\ref{eqv?}小节），以从左到右的顺序在整个子句的集合中进行。如果求值后\hyper{key}的值等于一个\hyper{case clause}的数据，对应的表达式被从左向右地求值，且\hyper{case clause}最后一个表达式的结果将作为{\cf case}表达式的结果被返回。如果求值后的\hyper{key}的值和每个子句中的数据都不一样，那么如果有一个{\cf else}子句的话，它的表达式被计算且最后一个的结果作为{\cf case}表达式的结果被返回；否则{\cf case}表达式的返回未定义的值。

\begin{scheme}
; 本示例已根据勘误表修改
(case (* 2 3)
  ((2 3 5 7) 'prime)
  ((4 6 8 9) 'composite))     \ev  composite
(case (car '(c d))
  ((a) 'a)
  ((b) 'b))                     \ev  \theunspecified
(case (car '(c d))
  ((a e i o u) 'vowel)
  ((w y) 'semivowel)
  (else 'consonant))            \ev  consonant%
\end{scheme}

一个\hyper{case clause}的最后一个\hyper{expression}在尾上下文中，如果{\cf case}表达式它自己在的话；见第\ref{basetailcontextsection}小节。

% A sample definition of {\cf case} in terms of simpler forms is in
% appendix~\ref{derivedformsappendix}.
\end{entry}


\begin{entry}{%
\proto{and}{ \hyperi{test} \dotsfoo}{\exprtype}}

\syntax \hyper{Test}必须是一个表达式。

\semantics 如果没有\hyper{test}，\schtrue{}被返回。否则\hyper{test}表达式被从左向右地求值，直到一个\hyper{test}返回\schfalse{}，或到达最后一个\hyper{test}。前一种情况下，{\cf and}表达式在不计算剩余表达式的情况下返回\schfalse{}。后一种情况，最后一个表达式被计算且它的值被返回。

\begin{scheme}
(and (= 2 2) (> 2 1))           \ev  \schtrue
(and (= 2 2) (< 2 1))           \ev  \schfalse
(and 1 2 'c '(f g))             \ev  (f g)
(and)                           \ev  \schtrue%
\end{scheme}

{\cf and}关键词可以使用{\cf syntax-rules}（见第\ref{syntaxrulessection}小节）根据{\cf if}进行定义，如下所示：

\begin{scheme}
(define-syntax \ide{and}
  (syntax-rules ()
    ((and) \sharpfoo{t})
    ((and test) test)
    ((and test1 test2 ...)
     (if test1 (and test2 ...) \sharpfoo{f}))))%
\end{scheme}

最后一个\hyper{test}表达式在尾上下文中，如果{\cf and}表达式它自己在的话；见第\ref{basetailcontextsection}小节。
\end{entry}


\begin{entry}{%
\proto{or}{ \hyperi{test} \dotsfoo}{\exprtype}}

\syntax \hyper{Test}必须是表达式。

\semantics 如果没有\hyper{test}，那么\schfalse{}被返回。否则，\hyper{test}按照从左到右的顺序被求值，直到一个\hyper{tesst}返回真值\var{val}（见第\ref{booleanvaluessection}小节），或到达最后一个\hyper{test}。在前一种情况，{\cf or}表达式在不计算剩余表达式的情况下返回\var{val}。后一种情况，最后一个表达式被求值，且它的值被返回。

\begin{scheme}
(or (= 2 2) (> 2 1))            \ev  \schtrue
(or (= 2 2) (< 2 1))            \ev  \schtrue
(or \schfalse \schfalse \schfalse) \ev  \schfalse
(or '(b c) (/ 3 0))             \ev  (b c)%
\end{scheme}

{\cf or}关键词可以使用{\cf syntax-rules}（见第\ref{syntaxrulessection}小节）根据{\cf if}进行定义，如下所示：

\begin{scheme}
(define-syntax \ide{or}
  (syntax-rules ()
    ((or) \sharpfoo{f})
    ((or test) test)
    ((or test1 test2 ...)
     (let ((x test1))
       (if x x (or test2 ...))))))%
\end{scheme}

最后一个\hyper{test}表达式在尾上下文中，如果{\cf or}表达式它自己也在的话；见第\ref{basetailcontextsection}小节。
\end{entry}


\subsection{绑定结构（Binding constructs）}

本节描述的绑定结构为变量创建本地绑定，它们只可以在一个限定的区域可见。结构{\cf let}, {\cf let*}, {\cf letrec}, 和{\cf letrec*}的语法是一样的，但是它们为它们的变量绑定建立的作用域（region）\index{region，作用域}（见\ref{variablesection}小节）是不一样的，且绑定的值计算的顺序是不一样的。在一个{\cf let}表达式中，初始值被计算在任何变量被绑定之前；在一个{\cf let*}表达式中，绑定和求值依次地执行。在一个{\cf letrec}或{\cf letrec*}表达式中，当所有的绑定正在被计算的时候所以的绑定生效，因此允许相互递归的定义。在一个{\cf letrec}表达式中，初始值在赋值给变量之前被计算；在一个{\cf letrec*}中，计算和赋值依次地进行。

此外，绑定结构{\cf let-values}和{\cf let*-values}使得{\cf let}和{\cf let*}更加通用，起允许多个变量绑定到值是多个值得表达式的结果。在建立作用域的方面，它们类似于{\cf let}和{\cf let*}：在一个{\cf let-values}表达式中，初始值被计算在任何变量被绑定之前；在一个{\cf let*-values}表达式中，绑定依次进行。

本节提到的所有绑定形式根据更简单形式的参考定义可以在附录\ref{derivedformsappendix}中找到。

\begin{entry}{%
\proto{let}{ \hyper{bindings} \hyper{body}}{\exprtype}}

\syntax
\hyper{Bindings}必须有形式
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
其中，每一个\hyper{init}是一个表达式，且\hyper{body}如第\ref{bodiessection}小节描述。在\hyper{variable}中任何变量不能出现超过一次。

\semantics
\hyper{Init}在当前的环境被求值（以一个未定义的顺序），\hyper{variable}被绑定到存有结果的新鲜的位置，\hyper{body}在扩展后的环境被求值，且\hyper{body}的最后一个表达式的值被返回。每个\hyper{variable}的绑定都将\hyper{body}作为它的作用域。\index{region，作用域}

\begin{scheme}
(let ((x 2) (y 3))
  (* x y))                      \ev  6

(let ((x 2) (y 3))
  (let ((x 7)
        (z (+ x y)))
    (* z x)))                   \ev  35%
\end{scheme}

另参见命名{\cf let}，见第\ref{namedlet}小节。

\end{entry}


\begin{entry}{%
\proto{let*}{ \hyper{bindings} \hyper{body}}{\exprtype}}\nobreak

\nobreak
\syntax
\hyper{Bindings}必须是形式
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm，%
\end{scheme}
其中，每一个\hyper{init}是一个表达式，且\hyper{body}如第\ref{bodiessection}小节描述。

\semantics
{\cf let*}形式类似于{\cf let}，但是\hyper{init}的求值和绑定的创建是从左向右顺序进行的，但其作用域不但包括\hyper{body}，还包括其右边的部分。因此，第二个\hyper{init}在第一个绑定可见且初始化的环境中被计算，以此类推。

\begin{scheme}
(let ((x 2) (y 3))
  (let* ((x 7)
         (z (+ x y)))
    (* z x)))             \ev  70%
\end{scheme}

\begin{note}
  通过{\cf let}表达式绑定的变量必须是不一样的，而通过{\cf let*}表达式绑定的变量则没有这个限制。
\end{note}
\end{entry}

\begin{entry}{%
\proto{letrec}{ \hyper{bindings} \hyper{body}}{\exprtype}}

\syntax
\hyper{Bindings}必须有形式
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
其中，每一个\hyper{init}是一个表达式，且\hyper{body}如第\ref{bodiessection}小节描述。在\hyper{variable}中任何变量不能出现超过一次。

\semantics
\hyper{variable}被绑定到新的位置，\hyper{init}在结果环境中被求值（以一些未定义的顺序），每一个\hyper{variable}被分配给对应的\hyper{init}的结果，\hyper{body}在结果环境中被求值，且\hyper{body}中最后一个表达式的值被返回。每个\hyper{variable}的绑定将整个{\cf letrec}表达式作为它的作用域\index{region，作用域}，这使得定义相互递归的过程成为可能。

\begin{scheme}
%(letrec ((x 2) (y 3))
%  (letrec ((foo (lambda (z) (+ x y z))) (x 7))
%    (foo 4)))                   \ev  14
%
(letrec ((even?
          (lambda (n)
            (if (zero? n)
                \schtrue
                (odd? (- n 1)))))
         (odd?
          (lambda (n)
            (if (zero? n)
                \schfalse
                (even? (- n 1))))))
  (even? 88))
                \ev  \schtrue%
\end{scheme}

在不赋值或引用任何\hyper{variable}的值的情况下，计算每个\hyper{init}应该是可能的。在{\cf letrec}的大部分常规使用中，所有的\hyper{init}是\lambdaexp{}表达式，此时限制被自动满足。另一个限制是，每个\hyper{init}的继续不能被调用多于一次。

\implresp 实现必须在\hyper{init}表达式求值（使用一个特定的求值顺序且顺序\hyper{init}表达式的值）期间检测\hyper{variable}的引用。如果实现检测到这样一个限制的违反，它必须抛出一个条件类型是{\cf\&assertion}的异常。实现可以也可以不检测每个\hyper{init}的继续是否被调用多于一次。可是，如果实现检测到的话，它必须抛出一个条件类型是{\cf\&assertion}的异常。
\end{entry}

\begin{entry}{%
\proto{letrec*}{ \hyper{bindings} \hyper{body}}{\exprtype}}

\syntax
\hyper{Bindings}必须有形式
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
其中，每一个\hyper{init}是一个表达式，且\hyper{body}如第\ref{bodiessection}小节描述。在\hyper{variable}中任何变量不能出现超过一次。

\semantics
\hyper{Variable}被绑定到新鲜的位置，每个\hyper{variable}被按从左向右的顺序分配给对应的\hyper{init}的求值结果，\hyper{body}在结果环境中被求值，且\hyper{body}中最后一个表达式的值被返回。尽管求值和赋值的顺序是从左向右的，但是每一个\hyper{variable}的绑定将整个{\cf letrec*}表达式作为其作用域\index{region，作用域}，这使得定义相互递归的过程成为可能。

\begin{scheme}
(letrec* ((p
           (lambda (x)
             (+ 1 (q (- x 1)))))
          (q
           (lambda (y)
             (if (zero? y)
                 0
                 (+ 1 (p (- y 1))))))
          (x (p 5))
          (y x))
  y)
                \ev  5%
\end{scheme}

在不赋值或引用对应的\hyper{variable}或任何在\hyper{bindings}跟随它的任何绑定的\hyper{variable}的值的情况下，计算每个\hyper{init}必须是可能的。另一个限制是每个\hyper{init}的继续不能被调用多于一次。

\implresp 实现必须在\hyper{init}表达式求值期间检测\hyper{variable}或任何在\hyper{bindings}跟随它的任何绑定的\hyper{variable}% TODO
的引用。如果实现检测到这样一个限制的违反，它必须抛出一个条件类型是{\cf\&assertion}的异常。实现可以也可以不检测每个\hyper{init}的继续是否被调用多于一次。可是，如果实现检测到的话，它必须抛出一个条件类型是{\cf\&assertion}的异常。
\end{entry}

\begin{entry}{%
\proto{let-values}{ \hyper{mv-bindings} \hyper{body}}{\exprtype}}

\syntax
\hyper{Mv-bindings}必须有形式
\begin{scheme}
((\hyperi{formals} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
其中，每一个\hyper{init}是一个表达式，且\hyper{body}如第\ref{bodiessection}小节描述。在\hyper{formals}集合中任何变量必须不能出现超过一次。

\semantics \hyper{Init}在当前的环境中被求值（以一些未定义的顺序），且出现在\hyper{formals}中的变量被绑定到包含\hyper{init}返回值的新鲜位置，其中\hyper{formals}匹配返回值就像\lambdaexp{}表达式中的\hyper{formals}在过程调用中匹配参数一样。然后，\hyper{body}在扩展后的环境中被求值，且\hyper{body}中最后一个表达式的值被返回。每个变量绑定将\hyper{body}作为它的作用域。\index{region，作用域}如果\hyper{formals}不匹配的话，那么一个条件类型是{\cf\&assertion}的异常被抛出。

\begin{scheme}
(let-values (((a b) (values 1 2))
             ((c d) (values 3 4)))
  (list a b c d)) \ev (1 2 3 4)

(let-values (((a b . c) (values 1 2 3 4)))
  (list a b c))            \ev (1 2 (3 4))

(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let-values (((a b) (values x y))
               ((x y) (values a b)))
    (list a b x y)))       \ev (x y a b)%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{let*-values}{ \hyper{mv-bindings} \hyper{body}}{\exprtype}}

\syntax
\hyper{Mv-bindings}必须有形式
\begin{scheme}
((\hyperi{formals} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
其中，每一个\hyper{init}是一个表达式，且\hyper{body}如第\ref{bodiessection}小节描述。在每个\hyper{formals}中，任何变量必须不能出现超过一次。

\semantics
{\cf let*-value}形式类似于{\cf let-value}，但是\hyper{init}被计算和绑定被创建是按从左到右的顺序进行的，每个\hyper{formals}绑定的作用域\index{region，作用域}除了\hyper{body}还包括它的右边。因此，第二个\hyper{init}在第一个\hyper{formals}可见且被初始化的环境中被求值，以此类推。

\begin{scheme}
(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let*-values (((a b) (values x y))
                ((x y) (values a b)))
    (list a b x y)))  \ev (x y x y)%
\end{scheme}

\begin{note}
  通过{\cf let-values}表达式绑定的变量必须是不一样的，而通过{\cf let*-values}表达式的不同\hyper{formals}绑定的变量则没有这个限制。
\end{note}

\end{entry}

\subsection{顺序结构（Sequencing）}\unsection

\begin{entry}{%
\proto{begin}{ \hyper{form} \dotsfoo}{\exprtype}
\rproto{begin}{ \hyper{expression} \hyper{expression} \dotsfoo}{\exprtype}}

\hyper{Begin}关键词有两个不同的作用，取决于它的上下文：
\begin{itemize}
\item 它可以作为一个形式出现在一个\hyper{body}中（见第\ref{bodiessection}小节），一个\hyper{library body}中（见第\ref{librarybodysection}小节），或一个\hyper{top-level body}（见第\ref{programchapter}章），或直接嵌套在一个内部的{\cf begin}形式中。在这种情况下，{\cf begin}形式必须有第一个标题行指定的形状。{\cf begin}的这种用法作为一种\defining{拼接（splicing）}形式—\hyper{body}里面的形式被拼接到内部周围，就好像原来的{\cf begin}包装不存在一样。

  \hyper{Body}或\hyper{library body}中的{\cf begin}形式必须是非空的，如果它在内部出现在第一个\hyper{expression}之后。

\item 它可以作为一个普通的表达式出现，且必须有第二个标题行指定的形状。在这种情况下，\hyper{expression}被按从左到右的顺序求值，且最后一个\hyper{expression}的值被返回。这种表达式类型被用作按顺序排列副作用，如赋值或输入输出。
\end{itemize}

\begin{scheme}
(define x 0)

(begin (set! x 5)
       (+ x 1))                  \ev  6

(begin (display "4 plus 1 equals ")
       (display (+ 4 1)))      \ev  \unspecified
 \>{\em 并打印}  4 plus 1 equals 5%
\end{scheme}
\end{entry}

\section{等价谓词（Equivalence predicates）}
\label{equivalencesection}

一个\defining{谓词}是一个总是返回布尔值（\schtrue{}或\schfalse{}）的过程。一个\defining{等价谓词}在计算上模拟数学上的等价关系（它是[对称的（symmetric），自反的（reflexive），且传递的（transitive）](/r6rs-translation-experience/#symmetric-reflexive-transitive)）。在本节表述的等价谓词中，{\cf eq?}是最好或最精细的，{\cf equal?}是最粗糙的。{\cf eqv?}比{\cf eq?}的辨别能力稍差。 \todo{Pitman doesn't like
this paragraph.  Lift the discussion from the Maclisp manual.  Explain
why there's more than one predicate.}


\begin{entry}{%
\proto{eqv?}{ \vari{obj} \varii{obj}}{procedure}}

{\cf eqv?}定义在对象上定义一个有用的等价关系。简单地说，它返回\schtrue{}，如果\vari{obj}和\varii{obj}在通常情况下被认为是相等的对象的话，否则返回\schfalse{}。这种关系不太好解释，但下面所列的{\cf eqv?}部分规范必须被所有的实现遵守。

{\cf eqv?}过程在以下情况返回\schtrue{}：

\begin{itemize}
\item \vari{Obj}和\varii{obj}都是布尔，且根据{\cf boolean=?}过程它们是一样的（第\ref{boolean=?}小节）。

\item \vari{Obj}和\varii{obj}都是符号，且根据{\cf symbol=?}过程它们是一样的（第\ref{symbol=?}小节）。

\item \vari{Obj}和\varii{obj}都是精确\index{exact，精确}数，且在数学上相等（见{\cf =}，第\ref{genericarithmeticsection}小节）。

\item \vari{Obj}和\varii{obj}都是非精确数字对象，且在数学上相等（见{\cf =}，第\ref{genericarithmeticsection}小节），且作为参数传递给任意其它可以通过Scheme标准算术过程定义的过程时产生的结果都是一样的（从{\cf eqv?}的意义上说），只要计算过程中不涉及非数。（本句已根据勘误表补全。）

\item \vari{Obj}和\varii{obj}都是字符，且根据{\cf char=?}过程它们是一样的（见第\ref{charactersection}小节）。

\item \vari{Obj}和\varii{obj}都是空表。

\item \vari{Obj}和\varii{obj}都是对象，比如点对，向量，字节向量（库的第\extref{lib:bytevectorschapter}{Bytevectors}章），字符串，记录（库的第\extref{lib:recordschapter}{Records}章），端口（库的第\extref{lib:portsiosection}{Port I/O}小节），或哈希表（库的第\extref{lib:hashtablechapter}{Hash tables}章），且指向相同的存储位置（第\ref{storagemodel}小节）。（原文中有一个重复的“哈希表”，已被删除。）

\item \vari{Obj}和\varii{obj}都是记录类型（record-type）描述符，它们在库的第\extref{lib:recordsproceduralsection}{Procedural layer}小节被指定为是{\cf eqv?}等价的。
\end{itemize}

{\cf eqv?}过程在以下情况返回\schfalse{}：

\begin{itemize}
\item \vari{Obj}和\varii{obj}是不同的类型（第\ref{disjointness}小节）。

\item \vari{Obj}和\varii{obj}是布尔，但{\cf boolean=?}过程返回\schfalse{}。

\item \vari{Obj}和\varii{obj}是符号，但{\cf symbol=?}过程返回\schfalse{}。

\item \vari{Obj}和\varii{obj}一个是精确数字对象，另一个是非精确数字对象。

\item \vari{Obj}和\varii{obj}是有理数字对象，但{\cf =}过程返回\schfalse{}。

\item \vari{Obj}和\varii{obj}作为参数传递给任意其它可以通过Scheme标准算术过程定义的过程时产生不一样的结果（从{\cf eqv?}的意义上说），只要计算过程中不涉及非数。（本句已根据勘误表补全。）

\item \vari{Obj}和\varii{obj}是字符，但{\cf char=?}过程返回\schfalse{}。

\item \vari{Obj}和\varii{obj}一个是空表，但另一个不是。% <!-- TODO：和类型不同重复 -->

\item \vari{Obj}和\varii{obj}是对象，比如点对，向量，字节向量（库的第\extref{lib:bytevectorschapter}{Bytevectors}章），字符串，记录（库的第\extref{lib:recordschapter}{Records}章），端口（库的第\extref{lib:portsiosection}{Port I/O}小节），或哈希表（库的第\extref{lib:hashtablechapter}{Hashtables}章），但指向不同的位置。

\item \vari{Obj}和\varii{obj}是点对，向量，字符串，或记录，或哈希表，向其内部应用相同的访问器（也就是{\cf car}, {\cf cdr}, {\cf vector-ref}, {\cf string-ref}, 或记录访问器）但产生的值在{\cf eqv?}下返回\schfalse{}。

\item \vari{Obj}和\varii{obj}是过程，但对于某些参数有不同的行为（返回不同的值或有不同的副作用）。

\end{itemize}

\begin{note}
  当\vari{obj}和\varii{obj}是数字对象时，{\cf eqv?}过程返回\schtrue{}并不意味着{\cf =}在相同的\vari{obj}和\varii{obj}参数下也返回\schtrue{}。
\end{note}


\begin{scheme}
(eqv? 'a 'a)                     \ev  \schtrue
(eqv? 'a 'b)                     \ev  \schfalse
(eqv? 2 2)                       \ev  \schtrue
(eqv? '() '())                   \ev  \schtrue
(eqv? 100000000 100000000)       \ev  \schtrue
(eqv? (cons 1 2) (cons 1 2))     \ev  \schfalse
(eqv? (lambda () 1)
      (lambda () 2))             \ev  \schfalse
(eqv? \#f 'nil)                  \ev  \schfalse%
\end{scheme}

下面的例子展示了上面的规则没有完全定义的{\cf eqv?}的行为。对于这些情况，我们只能说{\cf eqv?}的返回值必须是一个布尔。

\begin{scheme}
(let ((p (lambda (x) x)))
  (eqv? p p))                    \ev  \unspecified
(eqv? "" "")             \ev  \unspecified
(eqv? '\#() '\#())         \ev  \unspecified
(eqv? (lambda (x) x)
      (lambda (x) x))    \ev  \unspecified
(eqv? (lambda (x) x)
      (lambda (y) y))    \ev  \unspecified
(eqv? +nan.0 +nan.0)             \ev \unspecified%
\end{scheme}

下面的例子集合展示了对有本地状态的过程使用{\cf eqv?}的情况。对{\cf gen-counter}的每一次调用都必须付汇一个不同的过程，因为每个过程都有它自己内部的计数。{\cf gen-loser}的调用返回的过程被调用的时候行为是一样的。然而，{\cf eqv?}可以不检测这种相等。

\begin{scheme}
(define gen-counter
  (lambda ()
    (let ((n 0))
      (lambda () (set! n (+ n 1)) n))))
(let ((g (gen-counter)))
  (eqv? g g))           \ev  \unspecified
(eqv? (gen-counter) (gen-counter))
                        \ev  \schfalse
(define gen-loser
  (lambda ()
    (let ((n 0))
      (lambda () (set! n (+ n 1)) 27))))
(let ((g (gen-loser)))
  (eqv? g g))           \ev  \unspecified
(eqv? (gen-loser) (gen-loser))
                        \ev  \unspecified

(letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
         (g (lambda () (if (eqv? f g) 'both 'g))))
  (eqv? f g)) \ev  \unspecified

(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
         (g (lambda () (if (eqv? f g) 'g 'both))))
  (eqv? f g)) \ev  \schfalse%
\end{scheme}

实现可以在适当的时候在常量间共享结构。（根据勘误表，此处省略一句话。）因此，作用在常量上的{\cf eqv?}的返回值有时是实现定义的。

\begin{scheme}
(eqv? '(a) '(a))                 \ev  \unspecified
(eqv? "a" "a")                   \ev  \unspecified
(eqv? '(b) (cdr '(a b)))         \ev  \unspecified
(let ((x '(a)))
  (eqv? x x))                    \ev  \schtrue%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{eq?}{ \vari{obj} \varii{obj}}{procedure}}

{\cf eq?}谓词和{\cf eqv?}类似，除了在一些情况其识别差别的能力比{\cf eqv?}更加精细之外。

{\cf eq?}和{\cf eqv?}确保在符号，布尔，空表，点对，过程，非空字符串，字节向量，和向量，以及记录的行为是一样的。{\cf eq?}在数字对象，字符上的行为是实现定义的，但是它总是或者返回\schtrue{}或者返回\schfalse{}，且只有当{\cf eqv?}返回\schtrue{}时它才有可能返回\schtrue{}。{\cf eq?}谓词在空表，空向量，空字节向量和空字符串上的行为也可以是不一样的。

\begin{scheme}
(eq? 'a 'a)                     \ev  \schtrue
(eq? '(a) '(a))                 \ev  \unspecified
(eq? (list 'a) (list 'a))       \ev  \schfalse
(eq? "a" "a")                   \ev  \unspecified
(eq? "" "")                     \ev  \unspecified
(eq? '() '())                   \ev  \schtrue
(eq? 2 2)                       \ev  \unspecified
(eq? \#\backwhack{}A \#\backwhack{}A) \ev  \unspecified
(eq? car car)                   \ev  \unspecified （本条已根据勘误表修改）
(let ((n (+ 2 3)))
  (eq? n n))      \ev  \unspecified
(let ((x '(a)))
  (eq? x x))      \ev  \schtrue
(let ((x '\#()))
  (eq? x x))      \ev  \unspecified
(let ((p (lambda (x) x)))
  (eq? p p))      \ev  \unspecified%
\end{scheme}

\todo{Needs to be explained better above.  How can this be made to be
not confusing?  A table maybe?}

\end{entry}

\begin{entry}{%
\proto{equal?}{ \vari{obj} \varii{obj}}{procedure}}

{\cf equal?}谓词返回\schtrue{}当且仅当它的参数（可能无限地）到正则树（regular trees）的展开作为有序树是一样的（ordered trees）。% <!-- TODO -->

{\cf equal?}谓词对待点对和向量作为有出边（outgoing edges）的节点，使用{\cf string=?}比较字符串，使用{\cf bytevector=?}比较字节向量（见库的第\extref{lib:bytevectorschapter}{Bytevectors}章），且使用{\cf eqv?}比较其它节点。

\begin{scheme}
(equal? 'a 'a)                  \ev  \schtrue
(equal? '(a) '(a))              \ev  \schtrue
(equal? '(a (b) c)
        '(a (b) c))             \ev  \schtrue
(equal? "abc" "abc")            \ev  \schtrue
(equal? 2 2)                    \ev  \schtrue
(equal? (make-vector 5 'a)
        (make-vector 5 'a))     \ev  \schtrue
(equal? '\#vu8(1 2 3 4 5)
        (u8-list->bytevector
         '(1 2 3 4 5))          \ev  \schtrue
(equal? (lambda (x) x)
        (lambda (y) y))  \ev  \unspecified

(let* ((x (list 'a))
       (y (list 'a))
       (z (list x y)))
  (list (equal? z (list y x))
        (equal? z (list x x))))             \lev  (\schtrue{} \schtrue{})%
\end{scheme}

\begin{note}
  {\cf equal?}必须总是可以终止的，哪怕它的参数存在循环。
\end{note}

\end{entry}

\section{过程谓词（Procedure predicate）}

\begin{entry}{%
\proto{procedure?}{ obj}{procedure}}

返回\schtrue{}如果\var{obj}是一个过程，否则返回\schfalse{}。

\begin{scheme}
(procedure? car)            \ev  \schtrue
(procedure? 'car)           \ev  \schfalse
(procedure? (lambda (x) (* x x)))
                            \ev  \schtrue
(procedure? '(lambda (x) (* x x)))
                            \ev  \schfalse%
\end{scheme}

\end{entry}

\section{算术（Arithmetic）}
\label{genericarithmeticsection}

这里描述的过程实现了在第\ref{numbertypeschapter}章描述的数值塔上通用的算术。本节描述的通用过程既接受精确数也接受非精确数对象作为其参数，并根据它们参数的数值子类型执行强制转换和选取适当的操作。

库的第\extref{lib:numberchapter}{Arithmetic}章描述了定义其它数值过程的库。

\subsection{精确性和非精确性的传播（Propagation）}
\label{propagationsection}

下面列出的过程在传递给它们的参数都是精确的时候必须返回数学上正确的精确结果：

\begin{scheme}
+            -            *
max          min          abs
numerator    denominator  gcd
lcm          floor        ceiling
truncate     round        rationalize
real-part    imag-part    make-rectangular%
\end{scheme}

下面列出的过程当传递给它们的参数都是精确的且没有除数是零的时候必须返回正确的精确结果：

\begin{scheme}
/
div          mod           div-and-mod
div0         mod0          div0-and-mod0%
\end{scheme}

此外，过程{\cf expt}必须返回正确的精确结果，当传递给它的第一个参数是一个精确的实数对象且第二个参数是一个精确的整数对象。

通用的规则是，一般操作返回正确精确的结果，当所有传递给它们的参数都是精确的且结果是数学上明确定义的，但是当任何一个参数是非精确的时候返回一个非精确结果。这条规则的例外包括{\cf sqrt}, {\cf exp}, {\cf log}, {\cf sin}, {\cf cos}, {\cf tan}, {\cf asin}, {\cf acos}, {\cf atan}, {\cf expt}, {\cf make-polar}, {\cf magnitude}, 和{\cf angle}，其甚至可以（但不要求）在传递精确参数的时候返回非精确的结果，如这些过程的规范所示。

上面规则的一个普遍的例外是，一个实现可以返回一个精确结果尽管其参数是非精确的，但这个精确的结果对于所有可能的对这个非精确参数的精确替代，都应该是正确的。一个例子是{\cf (* 1.0 0)}，其可以返回{\cf 0}（精确地）或{\cf 0.0}（非精确的）。

\subsection{无穷大和非数的表示性}
\label{infinitiesnanssection}

数值操作的规范被书写就好像无穷大和非数是可以表示的，且指定许多操作，这些操作和数字对象相关，其在方法上和IEEE-754的二进制浮点算术标准相一致。Scheme的一个实现可以也可以不表示无穷大和非数；可是，一个实现必须抛出一个可继续的条件类型是{\cf\&no-infinities}或{\cf\&no-nans}（分别地见库的第\extref{lib:flonumssection}{Flonums}小节）的异常，在任何不能表示一个按规范说明的无穷大或非数的时候。在这种情况下，异常处理程序的继续是一个可以接受无穷大或非数的继续。这个要求也适用于数字对象和外部表示之间的转换，包括读取程序源代码。

\subsection{常用操作的语义（Semantics）}

一些操作是几个算术过程的语义基础。本节描述的这些操作的行为用作以后的参考。

\subsubsection{整数除法（Integer division）}
\label{integerdivision}

Scheme执行整数除法的操作依赖于数学操作$\mathrm{div}$, $\mathrm{mod}$, $\mathrm{div}_0$, 和$\mathrm{mod}_0$，它们定义如下：

$\mathrm{div}$, $\mathrm{mod}$, $\mathrm{div}_0$, 和$\mathrm{mod}_0$每个都接受两个实数$x_1$和$x_2$ 做为操作数，其中$x_2$ 必须是非零。

$\mathrm{div}$返回一个整数，$\mathrm{mod}$返回一个实数。它们的结果规定如下：
%
\begin{eqnarray*}
x_1~\mathrm{div}~x_2 &=& n_d\\
x_1~\mathrm{mod}~x_2 &=& x_m
\end{eqnarray*}
%
其中
%
\begin{displaymath}
\begin{array}{c}
x_1 = n_d \cdot x_2 + x_m\\
0 \leq x_m < |x_2|
\end{array}
\end{displaymath}
%
例子：
\begin{eqnarray*}
123~\mathrm{div}~10    &=&  12\\
123~\mathrm{mod}~10    &=&  3\\
123~\mathrm{div}~\textrm{$-10$}   &=&  -12\\
123~\mathrm{mod}~\textrm{$-10$}   &=&  3\\
-123~\mathrm{div}~10    &=&  -13\\
-123~\mathrm{mod}~10    &=&  7\\
-123~\mathrm{div}~\textrm{$-10$}   &=&  13\\
-123~\mathrm{mod}~\textrm{$-10$}   &=&  7
\end{eqnarray*}
%
$\mathrm{div}_0$和$\mathrm{mod}_0$与$\mathrm{div}$和$\mathrm{mod}$类似，除了$\mathrm{mod}_0$的结果在一个以零为中点的半开的区间中。它们的结果规定如下：
%
\begin{eqnarray*}
x_1~\mathrm{div}_0~x_2 &=& n_d\\
x_1~\mathrm{mod}_0~x_2 &=& x_m
\end{eqnarray*}
%
其中
%
\begin{displaymath}
\begin{array}{c}
x_1 = n_d \cdot x_2 + x_m\\
-|\frac{x_2}{2}| \leq x_m < |\frac{x_2}{2}|
\end{array}
\end{displaymath}
%
例子：
%
\begin{eqnarray*}
123~\mathrm{div}_0~10    &=&  12\\
123~\mathrm{mod}_0~10    &=&  3\\
123~\mathrm{div}_0~\textrm{$-10$}   &=&  -12\\
123~\mathrm{mod}_0~\textrm{$-10$}   &=&  3\\
-123~\mathrm{div}_0~10    &=&  -12\\
-123~\mathrm{mod}_0~10    &=&  -3\\
-123~\mathrm{div}_0~\textrm{$-10$}   &=&  12\\
-123~\mathrm{mod}_0~\textrm{$-10$}   &=&  -3
\end{eqnarray*}

\subsubsection{超越函数（Transcendental functions）}
\label{transcendentalfunctions}

In general, the transcendental functions $\log$, $\sin^{-1}$
(arcsine), $\cos^{-1}$ (arccosine), and $\tan^{-1}$ are multiply
defined.  The value of $\log z$ is defined to be the one whose
imaginary part lies in the range from $-\pi$ (inclusive if $-0.0$ is
distinguished, exclusive otherwise) to $\pi$ (inclusive).  $\log 0$ is
undefined.

The value of $\log z$ for non-real $z$ is defined in terms of log on real numbers as

\begin{displaymath}
\log z = \log |z| + (\mathrm{angle}~z)i
\end{displaymath}
%
where $\mathrm{angle}~z$ is the angle of $z = a\cdot e^{ib}$ specified
as:
$$\mathrm{angle}~z = b+2\pi n$$
with $-\pi \leq \mathrm{angle}~z\leq \pi$ and $\mathrm{angle}~z =
b+2\pi n$ for some integer $n$.

With the one-argument version of $\log$ defined this way, the values
of the two-argument-version of $\log$, $\sin^{-1} z$, $\cos^{-1} z$,
$\tan^{-1} z$, and the two-argument version of $\tan^{-1}$ are
according to the following formul\ae:
\begin{eqnarray*}
\log z~b &=& \frac{\log z}{\log b}\\
\sin^{-1} z &=& -i \log (i z + \sqrt{1 - z^2})\\
\cos^{-1} z &=& \pi / 2 - \sin^{-1} z\\
\tan^{-1} z &=& (\log (1 + i z) - \log (1 - i z)) / (2 i)\\
\tan^{-1} x~y &=& \mathrm{angle}(x+ yi)
\end{eqnarray*}

The range of $\tan^{-1} x~y$ is as in the following table. The
asterisk (*) indicates that the entry applies to implementations that
distinguish minus zero.

\begin{center}
\begin{tabular}{clll}
& $y$ condition & $x$ condition & range of result $r$\\\hline
& $y = 0.0$ & $x > 0.0$ & $0.0$\\
$\ast$ & $y = +0.0$  & $x > 0.0$ & $+0.0$\\
$\ast$ & $y = -0.0$ & $x > 0.0$ & $-0.0$\\
& $y > 0.0$ & $x > 0.0$ & $0.0 < r < \frac{\pi}{2}$\\
& $y > 0.0$ & $x = 0.0$ & $\frac{\pi}{2}$\\
& $y > 0.0$ & $x < 0.0$ & $\frac{\pi}{2} < r < \pi$\\
& $y = 0.0$ & $x < 0$ & $\pi$\\
$\ast$ & $y = +0.0$ & $x < 0.0$ & $\pi$\\
$\ast$ & $y = -0.0$ & $x < 0.0$ & $-\pi$\\
&$y < 0.0$ & $x < 0.0$ & $-\pi< r< -\frac{\pi}{2}$\\
&$y < 0.0$ & $x = 0.0$ & $-\frac{\pi}{2}$\\
&$y < 0.0$ & $x > 0.0$ & $-\frac{\pi}{2} < r< 0.0$\\
&$y = 0.0$ & $x = 0.0$ & undefined\\
$\ast$& $y = +0.0$ & $x = +0.0$ & $+0.0$\\
$\ast$& $y = -0.0$ & $x = +0.0$& $-0.0$\\
$\ast$& $y = +0.0$ & $x = -0.0$ & $\pi$\\
$\ast$& $y = -0.0$ & $x = -0.0$ & $-\pi$\\
$\ast$& $y = +0.0$ & $x = 0$ & $\frac{\pi}{2}$\\
$\ast$& $y = -0.0$ & $x = 0$    & $-\frac{\pi}{2}$
\end{tabular}
\end{center}

\subsection{Numerical operations}

\subsubsection{Numerical type predicates}

\begin{entry}{%
\proto{number?}{ obj}{procedure}
\proto{complex?}{ obj}{procedure}
\proto{real?}{ obj}{procedure}
\proto{rational?}{ obj}{procedure}
\proto{integer?}{ obj}{procedure}}

These numerical type predicates can be applied to any kind of
argument.  They return \schtrue{} if the object is a number object
of the named type, and \schfalse{} otherwise.
In general, if a type predicate is true of a number object then all higher
type predicates are also true of that number object.  Consequently, if a type
predicate is false of a number object, then all lower type predicates are
also false of that number object.

If \var{z} is a complex number object, then {\cf (real? \var{z})} is true if
and only if {\cf (zero? (imag-part \var{z}))} and {\cf (exact?
  (imag-part \var{z}))} are both true.

If \var{x} is a real number object, then {\cf (rational? \var{x})} is true if
and only if there exist exact integer objects \vari{k} and \varii{k} such that
{\cf (= \var{x} (/ \vari{k} \varii{k}))} and {\cf (= (numerator
  \var{x}) \vari{k})} and {\cf (= (denominator \var{x}) \varii{k})} are
all true.  Thus infinities and NaNs are not rational number objects.

If \var{q} is a rational number objects, then {\cf (integer?
\var{q})} is true if and only if {\cf (= (denominator
\var{q}) 1)} is true.  If \var{q} is not a rational number object,
then {\cf (integer? \var{q})} is \schfalse.

\begin{scheme}
(complex? 3+4i)                        \ev  \schtrue{}
(complex? 3)                           \ev  \schtrue{}
(real? 3)                              \ev  \schtrue{}
(real? -2.5+0.0i)                      \ev  \schfalse{}
(real? -2.5+0i)                        \ev  \schtrue{}
(real? -2.5)                           \ev  \schtrue{}
(real? \sharpsign{}e1e10)                         \ev  \schtrue{}
(rational? 6/10)                       \ev  \schtrue{}
(rational? 6/3)                        \ev  \schtrue{}
(rational? 2)                          \ev  \schtrue{}
(integer? 3+0i)                        \ev  \schtrue{}
(integer? 3.0)                         \ev  \schtrue{}
(integer? 8/4)                         \ev  \schtrue{}

(number? +nan.0)                       \ev  \schtrue{}
(complex? +nan.0)                      \ev  \schtrue{}
(real? +nan.0)                         \ev  \schtrue{}
(rational? +nan.0)                     \ev  \schfalse{}
(complex? +inf.0)                      \ev  \schtrue{}
(real? -inf.0)                         \ev  \schtrue{}
(rational? -inf.0)                     \ev  \schfalse{}
(integer? -inf.0)                      \ev  \schfalse{}%
\end{scheme}

\begin{note}
Except for {\cf number?}, the behavior of these type predicates
on inexact number objects is
unreliable, because any inaccuracy may
affect the result.
\end{note}
\end{entry}

\begin{entry}{%
\proto{real-valued?}{ obj}{procedure}
\proto{rational-valued?}{ obj}{procedure}
\proto{integer-valued?}{ obj}{procedure}}

These numerical type predicates can be applied to any kind of
argument.  The {\cf real-valued?} procedure
returns \schtrue{} if the object is a number object and is equal in the
sense of {\cf =} to some real number object, or if the object is a NaN, or a
complex number object whose real part is a NaN and whose imaginary
part is zero
in the sense of {\cf zero?}.  The {\cf rational-valued?} and {\cf
  integer-valued?} procedures return \schtrue{} if the object is a
number object and is equal in the sense of {\cf =} to some object of the
named type, and otherwise they return \schfalse{}.

\begin{scheme}
(real-valued? +nan.0)                  \ev  \schtrue{}
(real-valued? +nan.0+0i)                  \ev  \schtrue{}
(real-valued? -inf.0)                  \ev  \schtrue{}
(real-valued? 3)                       \ev  \schtrue{}
(real-valued? -2.5+0.0i)               \ev  \schtrue{}
(real-valued? -2.5+0i)                 \ev  \schtrue{}
(real-valued? -2.5)                    \ev  \schtrue{}
(real-valued? \sharpsign{}e1e10)                  \ev  \schtrue{}

(rational-valued? +nan.0)              \ev  \schfalse{}
(rational-valued? -inf.0)              \ev  \schfalse{}
(rational-valued? 6/10)                \ev  \schtrue{}
(rational-valued? 6/10+0.0i)           \ev  \schtrue{}
(rational-valued? 6/10+0i)             \ev  \schtrue{}
(rational-valued? 6/3)                 \ev  \schtrue{}

(integer-valued? 3+0i)                 \ev  \schtrue{}
(integer-valued? 3+0.0i)               \ev  \schtrue{}
(integer-valued? 3.0)                  \ev  \schtrue{}
(integer-valued? 3.0+0.0i)             \ev  \schtrue{}
(integer-valued? 8/4)                  \ev  \schtrue{}%
\end{scheme}

\begin{note}
  These procedures test whether a given number object can be coerced
  to the specified type without loss of numerical accuracy.
  Specifically, the behavior of these predicates differs from the
  behavior of {\cf real?}, {\cf rational?}, and {\cf integer?} on
  complex number objects whose imaginary part is inexact zero.
\end{note}

\begin{note}
The behavior of these type predicates on inexact number objects is
unreliable, because any inaccuracy may
affect the result.
\end{note}
\end{entry}

\begin{entry}{%
\proto{exact?}{ z}{procedure}
\proto{inexact?}{ z}{procedure}}

These numerical predicates provide tests for the exactness of a
quantity.  For any number object, precisely one of these predicates is
true.

\begin{scheme}
(exact? 5)                   \ev  \schtrue{}
(inexact? +inf.0)            \ev  \schtrue{}%
\end{scheme}
\end{entry}

\subsubsection{Generic conversions}

\begin{entry}{%
\proto{inexact}{ z}{procedure}
\proto{exact}{ z}{procedure}}

The {\cf inexact} procedure returns an inexact representation of \var{z}.  If
inexact number objects of the appropriate type have bounded precision, then
the value returned is an inexact number object that is nearest to the
argument.  If an exact argument has no reasonably close inexact
equivalent, an exception with condition type
{\cf\&implementation-violation} may be
raised.

\begin{note}
  For a real number object whose magnitude is finite but so large that it has
  no reasonable finite approximation as an inexact number, a
  reasonably close inexact equivalent may be {\cf +inf.0} or {\cf
    -inf.0}.  Similarly, the inexact representation of a complex
  number object whose components are finite may have infinite components.
\end{note}

The {\cf exact} procedure returns an exact representation of \var{z}.  The value
returned is the exact number object that is numerically closest to the
argument; in most cases, the result of this procedure should be
numerically equal to its argument.  If an inexact argument has no
reasonably close exact equivalent, an exception with condition type
{\cf\&implementation-violation} may be
raised.

These procedures implement the natural one-to-one correspondence
between exact and inexact integer objects throughout an
implementation-dependent range.

The {\cf inexact} and {\cf exact} procedures are idempotent.
\end{entry}

\subsubsection{Arithmetic operations}

\begin{entry}{%
\proto{=}{ \vari{z} \varii{z} \variii{z} \dotsfoo}{procedure}
\proto{<}{ \vari{x} \varii{x} \variii{x} \dotsfoo}{procedure}
\proto{>}{ \vari{x} \varii{x} \variii{x} \dotsfoo}{procedure}
\proto{<=}{ \vari{x} \varii{x} \variii{x} \dotsfoo}{procedure}
\proto{>=}{ \vari{x} \varii{x} \variii{x} \dotsfoo}{procedure}}

These procedures return \schtrue{} if their arguments are
(respectively): equal, monotonically increasing, monotonically
decreasing, monotonically nondecreasing, or monotonically
nonincreasing, and \schfalse{} otherwise.

\begin{scheme}
(= +inf.0 +inf.0)           \ev  \schtrue{}
(= -inf.0 +inf.0)           \ev  \schfalse{}
(= -inf.0 -inf.0)           \ev  \schtrue{}%
\end{scheme}

For any real number object \var{x} that is neither infinite nor NaN:

\begin{scheme}
(< -inf.0 \var{x} +inf.0))        \ev  \schtrue{}
(> +inf.0 \var{x} -inf.0))        \ev  \schtrue{}%
\end{scheme}

For any number object \var{z}:
%
\begin{scheme}
(= +nan.0 \var{z})               \ev  \schfalse{}%
\end{scheme}
%
For any real number object \var{x}:
%
\begin{scheme}
(< +nan.0 \var{x})               \ev  \schfalse{}
(> +nan.0 \var{x})               \ev  \schfalse{}%
\end{scheme}

These predicates must be transitive.

\begin{note}
The traditional implementations of these predicates in Lisp-like
languages are not transitive.
\end{note}

\begin{note}
While it is possible to compare inexact number objects using these
predicates, the results may be unreliable because a small inaccuracy
may affect the result; this is especially true of {\cf =} and {\cf zero?} (below).

When in doubt, consult a numerical analyst.
\end{note}
\end{entry}

\begin{entry}{%
\proto{zero?}{ z}{procedure}
\proto{positive?}{ x}{procedure}
\proto{negative?}{ x}{procedure}
\proto{odd?}{ n}{procedure}
\proto{even?}{ n}{procedure}
\proto{finite?}{ x}{procedure}
\proto{infinite?}{ x}{procedure}
\proto{nan?}{ x}{procedure}}

These numerical predicates test a number object for a particular property,
returning \schtrue{} or \schfalse{}.  The {\cf zero?}
procedure
tests if the number object is {\cf =} to zero, {\cf positive?} tests whether it is
greater than zero, {\cf negative?} tests whether it is less than zero, {\cf
  odd?} tests whether it is odd, {\cf even?} tests whether it is even, {\cf
  finite?} tests whether it is not an infinity and not a NaN, {\cf
  infinite?} tests whether it is an infinity, {\cf nan?} tests whether it is a
NaN.

\begin{scheme}
(zero? +0.0)                  \ev  \schtrue{}
(zero? -0.0)                  \ev  \schtrue{}
(zero? +nan.0)                \ev  \schfalse{}
(positive? +inf.0)            \ev  \schtrue{}
(negative? -inf.0)            \ev  \schtrue{}
(positive? +nan.0)            \ev  \schfalse{}
(negative? +nan.0)            \ev  \schfalse{}
(finite? +inf.0)              \ev  \schfalse{}
(finite? 5)                   \ev  \schtrue{}
(finite? 5.0)                 \ev  \schtrue{}
(infinite? 5.0)               \ev  \schfalse{}
(infinite? +inf.0)            \ev  \schtrue{}%
\end{scheme}

\begin{note}
  As with the predicates above, the results may be unreliable because
  a small inaccuracy may affect the result.
\end{note}
\end{entry}

\begin{entry}{%
\proto{max}{ \vari{x} \varii{x} \dotsfoo}{procedure}
\proto{min}{ \vari{x} \varii{x} \dotsfoo}{procedure}}

These procedures return the maximum or minimum of their arguments.

\begin{scheme}
(max 3 4)                              \ev  4
(max 3.9 4)                            \ev  4.0%
\end{scheme}

For any real number object \var{x}:

\begin{scheme}
(max +inf.0 \var{x})                         \ev  +inf.0
(min -inf.0 \var{x})                         \ev  -inf.0%
\end{scheme}

\begin{note}
If any argument is inexact, then the result is also inexact (unless
the procedure can prove that the inaccuracy is not large enough to affect the
result, which is possible only in unusual implementations).  If {\cf min} or
{\cf max} is used to compare number objects of mixed exactness, and the numerical
value of the result cannot be represented as an inexact number object without loss of
accuracy, then the procedure may raise an exception with condition
type {\cf\&implementation-restriction}.
\end{note}

\end{entry}

\begin{entry}{%
\proto{+}{ \vari{z} \dotsfoo}{procedure}
\proto{*}{ \vari{z} \dotsfoo}{procedure}}

These procedures return the sum or product of their arguments.

\begin{scheme}
(+ 3 4)                                \ev  7
(+ 3)                                  \ev  3
(+)                                    \ev  0
(+ +inf.0 +inf.0)                      \ev  +inf.0
(+ +inf.0 -inf.0)                      \ev  +nan.0

(* 4)                                  \ev  4
(*)                                    \ev  1
(* 5 +inf.0)                           \ev  +inf.0
(* -5 +inf.0)                          \ev  -inf.0
(* +inf.0 +inf.0)                      \ev  +inf.0
(* +inf.0 -inf.0)                      \ev  -inf.0
(* 0 +inf.0)                           \ev  0 \textnormal{\textit{or}} +nan.0
(* 0 +nan.0)                           \ev  0 \textnormal{\textit{or}} +nan.0
(* 1.0 0)                              \ev  0 \textnormal{\textit{or}} 0.0%
\end{scheme}

For any real number object \var{x} that is neither infinite nor NaN:

\begin{scheme}
(+ +inf.0 \var{x})                           \ev  +inf.0
(+ -inf.0 \var{x})                           \ev  -inf.0%
\end{scheme}

For any real number object \var{x}:

\begin{scheme}
(+ +nan.0 \var{x})                           \ev  +nan.0%
\end{scheme}

For any real number object \var{x} that is not an exact 0:

\begin{scheme}
(* +nan.0 \var{x})                           \ev  +nan.0%
\end{scheme}

If any of these procedures are applied to mixed non-rational real and
non-real complex arguments, they either raise an exception with
condition type {\cf\&implementation-restriction} or return an
unspecified number object.

Implementations that distinguish $-0.0$ should adopt behavior
consistent with the following examples:

\begin{scheme}
(+ 0.0 -0.0)  \ev 0.0
(+ -0.0 0.0)  \ev 0.0
(+ 0.0 0.0)   \ev 0.0
(+ -0.0 -0.0) \ev -0.0%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{-}{ z}{procedure}
\rproto{-}{ \vari{z} \varii{z} \dotsfoo}{procedure}}

With two or more arguments, this procedures returns the difference of
its arguments, associating to the left.  With one argument, however,
it returns the additive inverse of its argument.

\begin{scheme}
(- 3 4)                                \ev  -1
(- 3 4 5)                              \ev  -6
(- 3)                                  \ev  -3
(- +inf.0 +inf.0)                      \ev  +nan.0%
\end{scheme}

If this procedure is applied to mixed non-rational real and
non-real complex arguments, it either raises an exception with
condition type {\cf\&implementation-restriction} or returns an
unspecified number object.

Implementations that distinguish $-0.0$ should adopt behavior
consistent with the following examples:

\begin{scheme}
(- 0.0)       \ev -0.0
(- -0.0)      \ev 0.0
(- 0.0 -0.0)  \ev 0.0
(- -0.0 0.0)  \ev -0.0
(- 0.0 0.0)   \ev 0.0
(- -0.0 -0.0) \ev 0.0%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{/}{ z}{procedure}
\rproto{/}{ \vari{z} \varii{z} \dotsfoo}{procedure}}

\domain{If all of the arguments are exact, then the divisors must all
  be nonzero.}
With two or more arguments, this procedure returns the
quotient of its arguments, associating to the left.  With one
argument, however, it returns the multiplicative inverse
of its argument.

\begin{scheme}
(/ 3 4 5)                              \ev  3/20
(/ 3)                                  \ev  1/3
(/ 0.0)                                \ev  +inf.0
(/ 1.0 0)                              \ev  +inf.0
(/ -1 0.0)                             \ev  -inf.0
(/ +inf.0)                             \ev  0.0
(/ 0 0)                                \xev \exception{\&assertion}
(/ 3 0)                                \xev \exception{\&assertion}
(/ 0 3.5)                              \ev  0.0
(/ 0 0.0)                              \ev  +nan.0
(/ 0.0 0)                              \ev  +nan.0
(/ 0.0 0.0)                            \ev  +nan.0%
\end{scheme}

If this procedure is applied to mixed non-rational real and
non-real complex arguments, it either raises an exception with
condition type {\cf\&implementation-restriction} or returns an
unspecified number object.
\end{entry}

\begin{entry}{%
\proto{abs}{ x}{procedure}}

Returns the absolute value of its argument.

\begin{scheme}
(abs -7)                               \ev  7
(abs -inf.0)                           \ev  +inf.0%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{div-and-mod}{ \vari{x} \varii{x}}{procedure}
\proto{div}{ \vari{x} \varii{x}}{procedure}
\proto{mod}{ \vari{x} \varii{x}}{procedure}
\proto{div0-and-mod0}{ \vari{x} \varii{x}}{procedure}
\proto{div0}{ \vari{x} \varii{x}}{procedure}
\proto{mod0}{ \vari{x} \varii{x}}{procedure}}

These procedures implement number-theoretic integer division and
return the results of the corresponding mathematical operations
specified in section~\ref{integerdivision}.  In each case, \vari{x}
must be neither infinite nor a NaN, and \varii{x} must be nonzero;
otherwise, an exception with condition type {\cf\&assertion} is raised.

\begin{scheme}
(div \vari{x} \varii{x})         \ev \(\vari{x}~\mathrm{div}~\varii{x}\)
(mod \vari{x} \varii{x})         \ev \(\vari{x}~\mathrm{mod}~\varii{x}\)
(div-and-mod \vari{x} \varii{x})     \ev \(\vari{x}~\mathrm{div}~\varii{x}, \vari{x}~\mathrm{mod}~\varii{x}\)\\\>\>\>; \textrm{two return values}
(div0 \vari{x} \varii{x})        \ev \(\vari{x}~\mathrm{div}_0~\varii{x}\)
(mod0 \vari{x} \varii{x})        \ev \(\vari{x}~\mathrm{mod}_0~\varii{x}\)
(div0-and-mod0 \vari{x} \varii{x})   \lev \(\vari{x}~\mathrm{div}_0~\varii{x}, \vari{x}~\mathrm{mod}_0~\varii{x}\)\\\>\>; \textrm{two return values}%
\end{scheme}

\begin{entry}{%
\proto{gcd}{ \vari{n} \dotsfoo}{procedure}
\proto{lcm}{ \vari{n} \dotsfoo}{procedure}}

These procedures return the greatest common divisor or least common
multiple of their arguments.  The result is always non-negative.

\begin{scheme}
(gcd 32 -36)                           \ev  4
(gcd)                                  \ev  0
(lcm 32 -36)                           \ev  288
(lcm 32.0 -36)                         \ev  288.0
(lcm)                                  \ev  1%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{numerator}{ q}{procedure}
\proto{denominator}{ q}{procedure}}

These procedures return the numerator or denominator of their
argument; the result is computed as if the argument was represented as
a fraction in lowest terms.  The denominator is always positive.  The
denominator of $0$ is defined to be $1$.

\begin{scheme}
(numerator (/ 6 4))                    \ev  3
(denominator (/ 6 4))                  \ev  2
(denominator
  (inexact (/ 6 4)))                   \ev  2.0%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{floor}{ x}{procedure}
\proto{ceiling}{ x}{procedure}
\proto{truncate}{ x}{procedure}
\proto{round}{ x}{procedure}}

These procedures return inexact integer objects for inexact arguments that are
not infinities or NaNs, and exact integer objects for exact rational
arguments.  For such arguments, {\cf floor} returns the largest
integer object not larger than \var{x}.  The {\cf ceiling} procedure returns the smallest
integer object not smaller than \var{x}.  The {\cf truncate} procedure returns the integer
object closest to \var{x} whose absolute value is not larger than the
absolute value of \var{x}.  The {\cf round} procedure returns the
closest integer object to
\var{x}, rounding to even when \var{x} represents a number halfway between two
integers.

\begin{note}
If the argument to one of these procedures is inexact, then the result
is also inexact.  If an exact value is needed, the
result should be passed to the {\cf exact} procedure.
\end{note}

Although infinities and NaNs are not integer objects, these procedures return
an infinity when given an infinity as an argument, and a NaN when
given a NaN.

\begin{scheme}
(floor -4.3)                           \ev  -5.0
(ceiling -4.3)                         \ev  -4.0
(truncate -4.3)                        \ev  -4.0
(round -4.3)                           \ev  -4.0

(floor 3.5)                            \ev  3.0
(ceiling 3.5)                          \ev  4.0
(truncate 3.5)                         \ev  3.0
(round 3.5)                            \ev  4.0

(round 7/2)                            \ev  4
(round 7)                              \ev  7

(floor +inf.0)                         \ev  +inf.0
(ceiling -inf.0)                       \ev  -inf.0
(round +nan.0)                         \ev  +nan.0%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{rationalize}{ \vari{x} \varii{x}}{procedure}}

The {\cf rationalize} procedure returns the a number object
representing the {\em simplest} rational
number differing from \vari{x} by no more than \varii{x}.    A rational number $r_1$ is
{\em simpler} \mainindex{simplest rational} than another rational number
$r_2$ if $r_1 = p_1/q_1$ and $r_2 = p_2/q_2$ (in lowest terms) and $|p_1|
\leq |p_2|$ and $|q_1| \leq |q_2|$.  Thus $3/5$ is simpler than $4/7$.
Although not all rationals are comparable in this ordering (consider $2/7$
and $3/5$) any interval contains a rational number that is simpler than
every other rational number in that interval (the simpler $2/5$ lies
between $2/7$ and $3/5$).  Note that $0 = 0/1$ is the simplest rational of
all.
%
\begin{scheme}
(rationalize (exact .3) 1/10)          \lev 1/3
(rationalize .3 1/10)                  \lev \sharpsign{}i1/3  ; \textrm{approximately}

(rationalize +inf.0 3)                 \ev  +inf.0
(rationalize +inf.0 +inf.0)            \ev  +nan.0
(rationalize 3 +inf.0)                 \ev  0.0%
\end{scheme}
%
The first two examples hold only in implementations whose inexact real
number objects have sufficient precision.

\end{entry}

\begin{entry}{%
\proto{exp}{ z}{procedure}
\proto{log}{ z}{procedure}
\rproto{log}{ \vari{z} \varii{z}}{procedure}
\proto{sin}{ z}{procedure}
\proto{cos}{ z}{procedure}
\proto{tan}{ z}{procedure}
\proto{asin}{ z}{procedure}
\proto{acos}{ z}{procedure}
\proto{atan}{ z}{procedure}
\rproto{atan}{ \vari{x} \varii{x}}{procedure}}

These procedures compute the usual transcendental functions.  The {\cf
  exp} procedure computes the base-$e$ exponential of \var{z}.
The {\cf log} procedure with a single argument computes the natural logarithm of
\var{z} (not the base-ten logarithm); {\cf (log \vari{z}
  \varii{z})} computes the base-\varii{z} logarithm of \vari{z}.
The {\cf asin}, {\cf acos}, and {\cf atan} procedures compute arcsine,
arccosine, and arctangent, respectively.  The two-argument variant of
{\cf atan} computes {\cf (angle (make-rectangular \varii{x}
\vari{x}))}.

See section~\ref{transcendentalfunctions} for the underlying
mathematical operations. These procedures may return inexact results
even when given exact arguments.

\begin{scheme}
(exp +inf.0)                   \ev +inf.0
(exp -inf.0)                   \ev 0.0
(log +inf.0)                   \ev +inf.0
(log 0.0)                      \ev -inf.0
(log 0)                        \xev \exception{\&assertion}
(log -inf.0)                   \lev +inf.0+3.141592653589793i\\\> ; \textrm{approximately}
(atan -inf.0)                  \lev -1.5707963267948965 ; \textrm{approximately}
(atan +inf.0)                  \lev 1.5707963267948965 ; \textrm{approximately}
(log -1.0+0.0i)                \lev 0.0+3.141592653589793i ; \textrm{approximately}
(log -1.0-0.0i)                \lev 0.0-3.141592653589793i ; \textrm{approximately}\\\>; \textrm{if -0.0 is distinguished}%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{sqrt}{ z}{procedure}}

Returns the principal square root of \var{z}.  For rational \var{z},
the result has either positive real part, or zero real part and
non-negative imaginary part.  With $\log$ defined as in
section~\ref{transcendentalfunctions}, the value of {\cf (sqrt
  \var{z})} could be expressed as $e^{\frac{\log z}{2}}$.

The {\cf sqrt} procedure may return an inexact result even when given an exact
argument.

\begin{scheme}
(sqrt -5)                   \lev  0.0+2.23606797749979i ; \textrm{approximately}
(sqrt +inf.0)               \ev  +inf.0
(sqrt -inf.0)               \ev  +inf.0i%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{exact-integer-sqrt}{ k}{procedure}}

The {\cf exact-integer-sqrt} procedure returns two non-negative exact
integer objects $s$ and $r$ where $\var{k} = s^2 +
r$ and $\var{k} < (s+1)^2$.

\begin{scheme}
(exact-integer-sqrt 4) \ev 2 0\\\>\>\>; \textrm{two return values}
(exact-integer-sqrt 5) \ev 2 1\\\>\>\>; \textrm{two return values}
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{expt}{ \vari{z} \varii{z}}{procedure}}

Returns \vari{z} raised to the power \varii{z}.  For nonzero \vari{z},
this is $e^{z_2 \log z_1}$.
$0.0^{z}$ is $1.0$ if $\var{z} = 0.0$, and $0.0$ if {\cf
  (real-part \var{z})} is positive.  For other cases in which
the first argument is zero, either an exception is raised with
condition type {\cf\&implementation-restriction}, or an unspecified
number object is returned.

For an exact real number object \vari{z} and an exact
integer object \varii{z}, {\cf (expt \vari{z}
\varii{z})} must return an exact result.  For all other
values of \vari{z} and \varii{z}, {\cf (expt \vari{z}
\varii{z})} may return an inexact result, even when both
\vari{z} and \varii{z} are exact.

\begin{scheme}
(expt 5 3)                  \ev  125
(expt 5 -3)                 \ev  1/125
(expt 5 0)                  \ev  1
(expt 0 5)                  \ev  0
(expt 0 5+.0000312i)        \ev  0
(expt 0 -5)                 \ev  \unspecified
(expt 0 -5+.0000312i)       \ev  \unspecified
(expt 0 0)                  \ev  1
(expt 0.0 0.0)              \ev  1.0%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{make-rectangular}{ \vari{x} \varii{x}}{procedure}
\proto{make-polar}{ \variii{x} \variv{x}}{procedure}
\proto{real-part}{ z}{procedure}
\proto{imag-part}{ z}{procedure}
\proto{magnitude}{ z}{procedure}
\proto{angle}{ z}{procedure}}

Suppose $a_1$, $a_2$, $a_3$, and $a_4$ are real
numbers, and $c$ is a complex number such that the
following holds:
%
\begin{displaymath}
c = a_1 + a_2 i = a_3 e^{i a_4}
\end{displaymath}

Then, if \vari{x}, \varii{x}, \variii{x}, and \variv{x} are number
objects representing $a_1$, $a_2$, $a_3$, and $a_4$, respectively,
{\cf (make-rectangular \vari{x} \varii{x})} returns $c$, and {\cf
  (make-polar \variii{x} \variv{x})} returns $c$.
%
\begin{scheme}
(make-rectangular 1.1 2.2) \lev 1.1+2.2i ; \textrm{approximately}
(make-polar 1.1 2.2) \lev 1.1@2.2 ; \textrm{approximately}
\end{scheme}
%
Conversely, if $-\pi \leq a_4 \leq \pi$, and if $z$ is a number object
representing $c$, then {\cf (real-part \var{z})} returns $a_1$ {\cf
  (imag-part \var{z})} returns $a_2$, {\cf (magnitude \var{z})}
returns $a_3$, and {\cf (angle \var{z})} returns $a_4$.

\begin{scheme}
(real-part 1.1+2.2i)              \ev 1.1 ; \textrm{approximately}
(imag-part 1.1+2.2i)              \ev 2.2i ; \textrm{approximately}
(magnitude 1.1@2.2)              \ev 1.1 ; \textrm{approximately}
(angle 1.1@2.2)                  \ev 2.2 ; \textrm{approximately}

(angle -1.0)         \lev 3.141592653589793 ; \textrm{approximately}
(angle -1.0+0.0i)    \lev 3.141592653589793 ; \textrm{approximately}
(angle -1.0-0.0i)    \lev -3.141592653589793 ; \textrm{approximately}\\\>; \textrm{if -0.0 is distinguished}
(angle +inf.0)       \ev 0.0
(angle -inf.0)       \lev 3.141592653589793 ; \textrm{approximately}%
\end{scheme}

Moreover, suppose \vari{x}, \varii{x} are such that either \vari{x}
or \varii{x} is an infinity, then
%
\begin{scheme}
(make-rectangular \vari{x} \varii{x}) \ev \var{z}
(magnitude \var{z})              \ev +inf.0%
\end{scheme}
\end{entry}

The {\cf make-polar}, {\cf magnitude}, and
{\cf angle} procedures may return inexact results even when given exact
arguments.

\begin{scheme}
(angle -1)                    \lev 3.141592653589793 ; \textrm{approximately}
\end{scheme}
\end{entry}

\subsubsection{Numerical Input and Output}

\begin{entry}{%
\proto{number->string}{ z}{procedure}
\rproto{number->string}{ z radix}{procedure}
\rproto{number->string}{ z radix precision}{procedure}}

\var{Radix} must be an exact integer object, either 2, 8, 10, or 16.  If
omitted, \var{radix} defaults to 10.  If a \var{precision} is
specified, then \var{z} must be an inexact complex number object,
\var{precision} must be an exact positive integer object, and \var{radix}
must be 10.  The {\cf number->string} procedure takes a number object and a
radix and returns as a string an external representation of the given
number object in the given radix such that
%
\begin{scheme}
(let ((number \var{z}) (radix \var{radix}))
  (eqv? (string->number
          (number->string number radix)
          radix)
        number))%
\end{scheme}
%
is true.  If no possible result makes this expression
true, an exception with condition type
{\cf\&implementation-\hp{}restriction} is raised.

\begin{note}
The error case can occur only when \var{z} is not a complex number object
or is a complex number object with a non-rational real or imaginary part.
\end{note}

If a \var{precision} is specified, then the representations of the
inexact real components of the result, unless they are infinite or
NaN, specify an explicit \meta{mantissa width} \var{p}, and \var{p} is the
least $\var{p} \geq \var{precision}$ for which the above expression is
true.

If \var{z} is inexact, the radix is 10, and the above expression and
condition can be satisfied by a result that contains a decimal point,
then the result contains a decimal point and is expressed using the
minimum number of digits (exclusive of exponent, trailing zeroes, and
mantissa width) needed to make the above expression and condition
true~\cite{howtoprint,howtoread}; otherwise the format of the result
is unspecified.

The result returned by {\cf number->string} never contains an explicit
radix prefix.
\end{entry}

\begin{entry}{%
\proto{string->number}{ string}{procedure}
\rproto{string->number}{ string radix}{procedure}}

Returns a number object with maximally precise representation expressed by the
given \var{string}.  \var{Radix} must be an exact integer object, either 2, 8, 10,
or 16.  If supplied, \var{radix} is a default radix that may be overridden
by an explicit radix prefix in \var{string} (e.g., {\tt "\#o177"}).  If \var{radix}
is not supplied, then the default radix is 10.  If \var{string} is not
a syntactically valid notation for a number object or a notation for a
rational number object with a zero denominator, then {\cf string->number}
returns \schfalse{}.
%
\begin{scheme}
(string->number "100")                 \ev  100
(string->number "100" 16)              \ev  256
(string->number "1e2")                 \ev  100.0
(string->number "0/0")                 \ev  \schfalse
(string->number "+inf.0")              \ev  +inf.0
(string->number "-inf.0")              \ev  -inf.0
(string->number "+nan.0")              \ev  +nan.0%
\end{scheme}

\begin{note}
  The {\cf string->number} procedure always returns a number object or
  \schfalse{}; it never raises an exception.
\end{note}
\end{entry}


\section{Booleans}
\label{booleansection}

The standard boolean objects for true and false have external representations
\schtrue{} and \schfalse.\sharpindex{t}\sharpindex{f} However, of all
objects, only \schfalse{} counts as false in
conditional expressions.  See section~\ref{booleanvaluessection}.

\begin{note}
Programmers accustomed to other dialects of Lisp should be aware that
Scheme distinguishes both \schfalse{} and the empty list \index{empty list}
from each other and from the symbol \ide{nil}.
\end{note}

\begin{entry}{%
\proto{not}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is \schfalse, and returns
\schfalse{} otherwise.

\begin{scheme}
(not \schtrue)   \ev  \schfalse
(not 3)          \ev  \schfalse
(not (list 3))   \ev  \schfalse
(not \schfalse)  \ev  \schtrue
(not '())        \ev  \schfalse
(not (list))     \ev  \schfalse
(not 'nil)       \ev  \schfalse%
\end{scheme}

\end{entry}


\begin{entry}{%
\proto{boolean?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is either \schtrue{} or
\schfalse{} and returns \schfalse{} otherwise.

\begin{scheme}
(boolean? \schfalse)  \ev  \schtrue
(boolean? 0)          \ev  \schfalse
(boolean? '())        \ev  \schfalse%
\end{scheme}

\begin{entry}{%
\proto{boolean=?}{ \vari{bool} \varii{bool} \variii{bool}
  \dotsfoo}{procedure}}

Returns \schtrue{} if the booleans are the same.
\end{entry}

\end{entry}


\section{Pairs and lists}
\label{listsection}

A \defining{pair} is a
compound structure with two fields called the car and cdr fields (for
historical reasons).  Pairs are created by the procedure {\cf cons}.
The car and cdr fields are accessed by the procedures {\cf car} and
{\cf cdr}.

Pairs are used primarily to represent lists.  A list can
be defined recursively as either the empty list\index{empty list} or a pair whose
cdr is a list.  More precisely, the set of lists is defined as the smallest
set \var{X} such that

\begin{itemize}
\item The empty list is in \var{X}.
\item If \var{list} is in \var{X}, then any pair whose cdr field contains
      \var{list} is also in \var{X}.
\end{itemize}

The objects in the car fields of successive pairs of a list are the
elements of the list.  For example, a two-element list is a pair whose car
is the first element and whose cdr is a pair whose car is the second element
and whose cdr is the empty list.  The length of a list is the number of
elements, which is the same as the number of pairs.

The empty list\mainindex{empty list} is a special object of its own type.
It is not a pair.  It has no elements and its length is zero.

\begin{note}
The above definitions imply that all lists have finite length and are
terminated by the empty list.
\end{note}

A chain of pairs not ending in the empty list is called an
\defining{improper list}.  Note that an improper list is not a list.
The list and dotted notations can be combined to represent
improper lists:

\begin{scheme}
(a b c . d)%
\end{scheme}

is equivalent to

\begin{scheme}
(a . (b . (c . d)))%
\end{scheme}

Whether a given pair is a list depends upon what is stored in the cdr
field.

\begin{entry}{%
\proto{pair?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a pair, and otherwise
returns \schfalse.

\begin{scheme}
(pair? '(a . b))        \ev  \schtrue
(pair? '(a b c))        \ev  \schtrue
(pair? '())             \ev  \schfalse
(pair? '\#(a b))         \ev  \schfalse%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{cons}{ \vari{obj} \varii{obj}}{procedure}}

Returns a newly allocated pair whose car is \vari{obj} and whose cdr is
\varii{obj}.  The pair is guaranteed to be different (in the sense of
{\cf eqv?}) from every existing object.

\begin{scheme}
(cons 'a '())           \ev  (a)
(cons '(a) '(b c d))    \ev  ((a) b c d)
(cons "a" '(b c))       \ev  ("a" b c)
(cons 'a 3)             \ev  (a . 3)
(cons '(a b) 'c)        \ev  ((a b) . c)%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{car}{ pair}{procedure}}

Returns the contents of the car field of \var{pair}.

\begin{scheme}
(car '(a b c))          \ev  a
(car '((a) b c d))      \ev  (a)
(car '(1 . 2))          \ev  1
(car '())               \xev \exception{\&assertion}%
\end{scheme}

\end{entry}


\begin{entry}{%
\proto{cdr}{ pair}{procedure}}

Returns the contents of the cdr field of \var{pair}.

\begin{scheme}
(cdr '((a) b c d))      \ev  (b c d)
(cdr '(1 . 2))          \ev  2
(cdr '())               \xev \exception{\&assertion}%
\end{scheme}

\end{entry}



\setbox0\hbox{\tt(cadr \var{pair})}
\setbox1\hbox{procedure}


\begin{entry}{%
\proto{caar}{ pair}{procedure}
\proto{cadr}{ pair}{procedure}
\texonly
\pproto{\hbox to 1\wd0 {\hfil$\vdots$\hfil}}{\hbox to 1\wd1 {\hfil$\vdots$\hfil}}
\endtexonly
\htmlonly $\vdots$ \endhtmlonly
\proto{cdddar}{ pair}{procedure}
\proto{cddddr}{ pair}{procedure}}

These procedures are compositions of {\cf car} and {\cf cdr}, where
for example {\cf caddr} could be defined by

\begin{scheme}
(define caddr (lambda (x) (car (cdr (cdr x))))){\rm.}%
\end{scheme}

Arbitrary compositions, up to four deep, are provided.  There are
twenty-eight of these procedures in all.

\end{entry}


\begin{entry}{%
\proto{null?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is the empty list\index{empty list},
\schfalse otherwise.

\end{entry}

\begin{entry}{%
\proto{list?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a list, \schfalse{} otherwise.
By definition, all lists are chains of pairs that have finite length and are terminated by
the empty list.

\begin{scheme}
(list? '(a b c))     \ev  \schtrue
(list? '())          \ev  \schtrue
(list? '(a . b))     \ev  \schfalse%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{list}{ \var{obj} \dotsfoo}{procedure}}

Returns a newly allocated list of its arguments.

\begin{scheme}
(list 'a (+ 3 4) 'c)            \ev  (a 7 c)
(list)                          \ev  ()%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{length}{ list}{procedure}}

Returns the length of \var{list}.

\begin{scheme}
(length '(a b c))               \ev  3
(length '(a (b) (c d e)))       \ev  3
(length '())                    \ev  0%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{append}{ list \dotsfoo{} obj}{procedure}}

Returns a possibly improper list consisting of the elements of the first \var{list}
followed by the elements of the other \var{list}s, with \var{obj} as
the cdr of the final pair.
An improper list results if \var{obj} is not a
list.

\begin{scheme}
(append '(x) '(y))              \ev  (x y)
(append '(a) '(b c d))          \ev  (a b c d)
(append '(a (b)) '((c)))        \ev  (a (b) (c))
(append '(a b) '(c . d))        \ev  (a b c . d)
(append '() 'a)                 \ev  a%
\end{scheme}

If {\cf append} constructs a nonempty chain of pairs, it is always
newly allocated.  If no pairs are allocated, \var{obj} is returned.
\end{entry}


\begin{entry}{%
\proto{reverse}{ list}{procedure}}

Returns a newly allocated list consisting of the elements of \var{list}
in reverse order.

\begin{scheme}
(reverse '(a b c))              \ev  (c b a)
(reverse '(a (b c) d (e (f))))  \lev  ((e (f)) d (b c) a)%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{list-tail}{ list k}{procedure}}

\domain{\var{List} should be a list of size at least \var{k}.}
The {\cf list-tail} procedure returns the subchain of pairs of \var{list}
obtained by omitting the first \var{k} elements.

\begin{scheme}
(list-tail '(a b c d) 2)                 \ev  (c d)%
\end{scheme}

\implresp The implementation must check that \var{list} is a chain of
pairs whose length is at least \var{k}.  It should not check that it is a chain
of pairs beyond this length.
\end{entry}


\begin{entry}{%
\proto{list-ref}{ list k}{procedure}}

\domain{\var{List} must be a list whose length is at least $\var{k}+1$.}
The {\cf list-tail} procedure returns the \var{k}th element of \var{list}.

\begin{scheme}
(list-ref '(a b c d) 2)                 \ev c%
\end{scheme}

\implresp The implementation must check that \var{list} is a chain of
pairs whose length is at least $\var{k}+1$.  It should not check that it is a list
of pairs beyond this length.
\end{entry}


\begin{entry}{%
\proto{map}{ proc \vari{list} \varii{list} \dotsfoo}{procedure}}

\domain{The \var{list}s should all have the same length.  \var{Proc}
  should accept as many arguments as there are
  \var{list}s and return a single value.  \var{Proc} should not mutate
  any of the \var{list}s.}

The {\cf map} procedure applies \var{proc} element-wise to the elements of the
\var{list}s and returns a list of the results, in order.
\var{Proc} is always called in the same dynamic environment
as {\cf map} itself.
The order in which \var{proc} is applied to the elements of the
\var{list}s is unspecified.
If multiple returns occur from {\cf map}, the
values returned by earlier returns are not mutated.

\begin{scheme}
(map cadr '((a b) (d e) (g h)))   \lev  (b e h)

(map (lambda (n) (expt n n))
     '(1 2 3 4 5))                \lev  (1 4 27 256 3125)

(map + '(1 2 3) '(4 5 6))         \ev  (5 7 9)

(let ((count 0))
  (map (lambda (ignored)
         (set! count (+ count 1))
         count)
       '(a b)))                 \ev  (1 2) \var{or} (2 1)%
\end{scheme}

\implresp The implementation should check that the \var{list}s all
have the same length.  The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.  An
implementation may check whether \var{proc} is an appropriate argument
before applying it.
\end{entry}


\begin{entry}{%
\proto{for-each}{ proc \vari{list} \varii{list} \dotsfoo}{procedure}}

\domain{The \var{list}s should all have the same length.  \var{Proc}
  should accept as many arguments as there are
  \var{list}s.  \var{Proc} should not mutate
  any of the \var{list}s.}

The {\cf for-each} procedure applies \var{proc}
element-wise to the elements of the
\var{list}s for its side effects,  in order from the first elements to the
last.
\var{Proc} is always called in the same dynamic environment
as {\cf for-each} itself.
The return values of {\cf for-each} \areunspecified.

\begin{scheme}
(let ((v (make-vector 5)))
  (for-each (lambda (i)
              (vector-set! v i (* i i)))
            '(0 1 2 3 4))
  v)                                \ev  \#(0 1 4 9 16)

(for-each (lambda (x) x) '(1 2 3 4)) \lev \theunspecified

(for-each even? '()) \ev \theunspecified%
\end{scheme}

\implresp The implementation should check that the \var{list}s all
have the same length.  The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.
An implementation may check whether \var{proc} is an appropriate argument
before applying it.

\begin{note}
Implementations of {\cf for-each} may or may not tail-call
\var{proc} on the last elements.
\end{note}

\end{entry}


\section{Symbols}
\label{symbolsection}

Symbols are objects whose usefulness rests on the fact that two
symbols are identical (in the sense of {\cf eq?}, {\cf eqv?} and {\cf equal?}) if and only if their
names are spelled the same way.
A symbol literal is formed using {\cf quote}.

\begin{entry}{%
\proto{symbol?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a symbol, otherwise returns \schfalse.

\begin{scheme}
(symbol? 'foo)          \ev  \schtrue
(symbol? (car '(a b)))  \ev  \schtrue
(symbol? "bar")         \ev  \schfalse
(symbol? 'nil)          \ev  \schtrue
(symbol? '())           \ev  \schfalse
(symbol? \schfalse)     \ev  \schfalse%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{symbol->string}{ symbol}{procedure}}

Returns the name of \var{symbol} as an immutable string.

\begin{scheme}
(symbol->string 'flying-fish)
                                  \ev  "flying-fish"
(symbol->string 'Martin)          \ev  "Martin"
(symbol->string
   (string->symbol "Malvina"))
                                  \ev  "Malvina"%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{symbol=?}{ \vari{symbol} \varii{symbol} \variii{symbol}
  \dotsfoo}{procedure}}

Returns \schtrue{} if the symbols are the same, i.e., if their names
are spelled the same.
\end{entry}

\begin{entry}{%
\proto{string->symbol}{ string}{procedure}}

Returns the symbol whose name is \var{string}.

\begin{scheme}
(eq? 'mISSISSIppi 'mississippi)  \lev  \schfalse
(string->symbol "mISSISSIppi")  \lev%
  {\rm{}the symbol with name} "mISSISSIppi"
(eq? 'bitBlt (string->symbol "bitBlt"))     \lev  \schtrue
(eq? 'JollyWog
     (string->symbol
       (symbol->string 'JollyWog)))  \lev  \schtrue
(string=? "K. Harper, M.D."
          (symbol->string
            (string->symbol "K. Harper, M.D.")))  \lev  \schtrue%
\end{scheme}

\end{entry}


\section{Characters}
\label{charactersection}

\mainindex{Unicode}
\mainindex{scalar value}

\defining{Characters} are objects that represent Unicode scalar
values~\cite{Unicode}.

\begin{note}
  Unicode defines a standard mapping between sequences of
  \textit{Unicode scalar values}\mainindex{Unicode scalar
    value}\mainindex{scalar value} (integers in the range 0 to
  \#x10FFFF, excluding the range \#xD800 to \#xDFFF) in the latest
  version of the standard and human-readable ``characters''. More
  precisely, Unicode distinguishes between glyphs, which are printed
  for humans to read, and characters, which are abstract entities that
  map to glyphs (sometimes in a way that's sensitive to surrounding
  characters).  Furthermore, different sequences of scalar values
  sometimes correspond to the same character.  The relationships among
  scalar, characters, and glyphs are subtle and complex.

  Despite this complexity, most things that a literate human would
  call a ``character'' can be represented by a single Unicode scalar
  value (although several sequences of Unicode scalar values may
  represent that same character). For example, Roman letters, Cyrillic
  letters, Hebrew consonants, and most Chinese characters fall into
  this category.

  Unicode scalar values exclude the range \#xD800 to \#xDFFF, which
  are part of the range of Unicode \textit{code points}\mainindex{code
    point}.  However, the Unicode code points in this range,
  the so-called \textit{surrogates}\mainindex{surrogate}, are an
  artifact of the UTF-16 encoding, and can only appear in specific
  Unicode encodings, and even then only in pairs that encode scalar
  values.  Consequently, all characters represent code points, but the
  surrogate code points do not have representations as characters.
\end{note}

\begin{entry}{%
\proto{char?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a character, otherwise returns \schfalse.

\end{entry}

\begin{entry}{%
\proto{char->integer}{ char}{procedure}
\proto{integer->char}{ \vr{sv}}{procedure}}

\domain{\var{Sv} must be a Unicode scalar value, i.e., a non-negative exact
  integer object in $\left[0, \#x\textrm{D7FF}\right] \cup
  \left[\#x\textrm{E000}, \#x\textrm{10FFFF}\right]$.}

Given a character, {\cf char\coerce{}integer} returns its Unicode scalar value
as an exact integer object.
For a Unicode scalar value \var{sv}, {\cf integer\coerce{}char}
returns its associated character.

\begin{scheme}
(integer->char 32) \ev \sharpsign\backwhack{}space
(char->integer (integer->char 5000))
\ev 5000
(integer->char \sharpsign{}\backwhack{}xD800) \xev \exception{\&assertion}%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{char=?}{ \vari{char} \varii{char} \variii{char} \dotsfoo}{procedure}
\proto{char<?}{ \vari{char} \varii{char} \variii{char} \dotsfoo}{procedure}
\proto{char>?}{ \vari{char} \varii{char} \variii{char} \dotsfoo}{procedure}
\proto{char<=?}{ \vari{char} \varii{char} \variii{char} \dotsfoo}{procedure}
\proto{char>=?}{ \vari{char} \varii{char} \variii{char} \dotsfoo}{procedure}}

\label{characterequality}
These procedures impose a total ordering on the set of characters
according to their Unicode scalar values.

\begin{scheme}
(char<? \sharpsign\backwhack{}z \sharpsign\backwhack{}\ss) \ev \schtrue
(char<? \sharpsign\backwhack{}z \sharpsign\backwhack{}Z) \ev \schfalse%
\end{scheme}

\end{entry}

\section{Strings}
\label{stringsection}

Strings are sequences of characters.

\vest The {\em length} of a string is the number of characters that it
contains.  This number is fixed when the
string is created.  The \defining{valid indices} of a string are the
integers less than the length of the string.  The first
character of a string has index 0, the second has index 1, and so on.

\begin{entry}{%
\proto{string?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a string, otherwise returns \schfalse.
\end{entry}


\begin{entry}{%
\proto{make-string}{ k}{procedure}
\rproto{make-string}{ k char}{procedure}}

Returns a newly allocated string of
length \var{k}.  If \var{char} is given, then all elements of the string
are initialized to \var{char}, otherwise the contents of the
\var{string} are unspecified.

\end{entry}

\begin{entry}{%
\proto{string}{ char \dotsfoo}{procedure}}

Returns a newly allocated string composed of the arguments.

\end{entry}

\begin{entry}{%
\proto{string-length}{ string}{procedure}}

Returns the number of characters in the given \var{string} as an exact
integer object.
\end{entry}


\begin{entry}{%
\proto{string-ref}{ string k}{procedure}}

\domain{\var{K} must be a valid index of \var{string}.}
The {\cf string-ref} procedure returns character \vr{k} of \var{string} using zero-origin indexing.

\begin{note}
  Implementors should make {\cf string-ref} run in constant
  time.
\end{note}
\end{entry}

\begin{entry}{%
\proto{string=?}{ \vari{string} \varii{string} \variii{string} \dotsfoo}{procedure}}

Returns \schtrue{} if the strings are the same length and contain the same
characters in the same positions.  Otherwise, the {\cf string=?}
procedure returns \schfalse.

\begin{scheme}
(string=? "Stra\ss{}e" "Strasse") \lev \schfalse%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{string<?}{ \vari{string} \varii{string} \variii{string} \dotsfoo}{procedure}
\proto{string>?}{ \vari{string} \varii{string} \variii{string} \dotsfoo}{procedure}
\proto{string<=?}{ \vari{string} \varii{string} \variii{string} \dotsfoo}{procedure}
\proto{string>=?}{ \vari{string} \varii{string} \variii{string} \dotsfoo}{procedure}}

These procedures are the lexicographic extensions to strings of the
corresponding orderings on characters.  For example, {\cf string<?}\ is
the lexicographic ordering on strings induced by the ordering
{\cf char<?}\ on characters.  If two strings differ in length but
are the same up to the length of the shorter string, the shorter string
is considered to be lexicographically less than the longer string.

\begin{scheme}
(string<? "z" "\ss") \ev \schtrue
(string<? "z" "zz") \ev \schtrue
(string<? "z" "Z") \ev \schfalse%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{substring}{ string start end}{procedure}}

\domain{\var{String} must be a string, and \var{start} and \var{end}
must be exact integer objects satisfying
$$0 \leq \var{start} \leq \var{end} \leq \hbox{\tt(string-length \var{string})\rm.}$$}
The {\cf substring} procedure returns a newly allocated string formed from the characters of
\var{string} beginning with index \var{start} (inclusive) and ending with index
\var{end} (exclusive).
\end{entry}


\begin{entry}{%
\proto{string-append}{ \var{string} \dotsfoo}{procedure}}

Returns a newly allocated string whose characters form the concatenation of the
given strings.
\end{entry}


\begin{entry}{%
\proto{string->list}{ string}{procedure}
\proto{list->string}{ list}{procedure}}

\domain{\var{List} must be a list of characters.}
The {\cf string\coerce{}list} procedure returns a newly allocated list of the
characters that make up the given string.  The {\cf
  list\coerce{}string} procedure
returns a newly allocated string formed from the characters in
\var{list}. The {\cf string\coerce{}list}
and {\cf list\coerce{}string} procedures are
inverses so far as {\cf equal?}\ is concerned.
\end{entry}

\begin{entry}{%
\proto{string-for-each}{ proc \vari{string} \varii{string} \dotsfoo}{procedure}}

\domain{The \var{string}s must all have the same length.  \var{Proc}
  should accept as many arguments as there are {\it string}s.}
The {\cf string-for-each} procedure applies \var{proc}
element-wise to the characters of the
\var{string}s for its side effects,  in order from the first characters to the
last.
\var{Proc} is always called in the same dynamic environment
as {\cf string-for-each} itself.
The return values of {\cf string-for-each} \areunspecified.

Analogous to {\cf for-each}.

\implresp The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.
An
implementation may check whether \var{proc} is an appropriate argument
before applying it.
\end{entry}

\begin{entry}{%
\proto{string-copy}{ string}{procedure}}

Returns a newly allocated copy of the given \var{string}.

\end{entry}

\section{Vectors}
\label{vectorsection}

Vectors are heterogeneous structures whose elements are indexed
by integers.  A vector typically occupies less space than a list
of the same length, and the average time needed to access a randomly
chosen element is typically less for the vector than for the list.

\vest The {\em length} of a vector is the number of elements that it
contains.  This number is a non-negative integer that is fixed when the
vector is created.
The {\em valid indices}\index{valid indices} of a
vector are the exact non-negative integer objects less than the length of the
vector.  The first element in a vector is indexed by zero, and the last
element is indexed by one less than the length of the vector.

Like list constants, vector constants must be quoted:

\begin{scheme}
'\#(0 (2 2 2 2) "Anna")  \lev  \#(0 (2 2 2 2) "Anna")%
\end{scheme}

\begin{entry}{%
\proto{vector?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a vector.  Otherwise the procedure
returns \schfalse.
\end{entry}


\begin{entry}{%
\proto{make-vector}{ k}{procedure}
\rproto{make-vector}{ k fill}{procedure}}

Returns a newly allocated vector of \var{k} elements.  If a second
argument is given, then each element is initialized to \var{fill}.
Otherwise the initial contents of each element is unspecified.

\end{entry}


\begin{entry}{%
\proto{vector}{ obj \dotsfoo}{procedure}}

Returns a newly allocated vector whose elements contain the given
arguments.  Analogous to {\cf list}.

\begin{scheme}
(vector 'a 'b 'c)               \ev  \#(a b c)%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{vector-length}{ vector}{procedure}}

Returns the number of elements in \var{vector} as an exact integer object.
\end{entry}


\begin{entry}{%
\proto{vector-ref}{ vector k}{procedure}}

\domain{\var{K} must be a valid index of \var{vector}.}
The {\cf vector-ref} procedure returns the contents of element \vr{k} of
\var{vector}.

\begin{scheme}
(vector-ref '\#(1 1 2 3 5 8 13 21) 5)  \lev  8%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{vector-set!}{ vector k obj}{procedure}}

\domain{\var{K} must be a valid index of \var{vector}.}
The {\cf vector-set!} procedure stores \var{obj} in element \vr{k} of
\var{vector}, and returns \unspecifiedreturn.

Passing an immutable vector to {\cf vector-set!} should cause an exception
with condition type {\cf\&assertion} to be raised.

\begin{scheme}
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
  (vector-set! vec 1 '("Sue" "Sue"))
  vec)      \lev  \#(0 ("Sue" "Sue") "Anna")

(vector-set! '\#(0 1 2) 1 "doe")  \lev  \unspecified
             ; \textrm{constant vector}
             ; \textrm{should raise} \exception{\&assertion}%
\end{scheme}

\end{entry}


\begin{entry}{%
\proto{vector->list}{ vector}{procedure}
\proto{list->vector}{ list}{procedure}}

The {\cf vector->list} procedure returns a newly allocated list of the objects contained
in the elements of \var{vector}.  The {\cf list->vector} procedure returns a newly
created vector initialized to the elements of the list \var{list}.

\begin{scheme}
(vector->list '\#(dah dah didah))  \lev  (dah dah didah)
(list->vector '(dididit dah))   \lev  \#(dididit dah)%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{vector-fill!}{ vector fill}{procedure}}

Stores \var{fill} in every element of \var{vector}
and returns \unspecifiedreturn.
\end{entry}

\begin{entry}{%
\proto{vector-map}{ proc \vari{vector} \varii{vector} \dotsfoo}{procedure}}

\domain{The \var{vector}s must all have the same length.  \var{Proc}
  should accept as many arguments as there are {\it vector}s and return a
  single value.}

The {\cf vector-map} procedure applies \var{proc} element-wise to the elements of the
\var{vector}s and returns a vector of the results, in order.
\var{Proc} is always called in the same dynamic environment
as {\cf vector-map} itself.
The order in which \var{proc} is applied to the elements of the
\var{vector}s is unspecified.
If multiple returns occur from {\cf vector-map}, the return
values returned by earlier returns are not mutated.


Analogous to {\cf map}.

\implresp The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.
An
implementation may check whether \var{proc} is an appropriate argument
before applying it.
\end{entry}


\begin{entry}{%
\proto{vector-for-each}{ proc \vari{vector} \varii{vector} \dotsfoo}{procedure}}

\domain{The \var{vector}s must all have the same length.  \var{Proc}
  should accept as many arguments as there are {\it vector}s.}
The {\cf vector-for-each} procedure applies \var{proc}
element-wise to the elements of the
\var{vector}s for its side effects,  in order from the first elements to the
last.
\var{Proc} is always called in the same dynamic environment
as {\cf vector-for-each} itself.
The return values of {\cf vector-for-each} \areunspecified.

Analogous to {\cf for-each}.

\implresp The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.
An
implementation may check whether \var{proc} is an appropriate argument
before applying it.
\end{entry}

\section{Errors and violations}
\label{errorviolation}

\begin{entry}{%
\proto{error}{ who message \vari{irritant} \dotsfoo}{procedure}
\proto{assertion-violation}{ who message \vari{irritant} \dotsfoo}{procedure}}

\domain{\var{Who} must be a string or a symbol or \schfalse{}.
  \var{Message} must be a string.
  The \var{irritant}s are arbitrary objects.}

These procedures raise an exception.  The {\cf error}
procedure should be called when an error has occurred, typically caused by
something that has gone wrong in the interaction of the program with the
external world or the user.  The {\cf assertion-violation} procedure
should be called when an invalid call to a procedure was made, either passing an
invalid number of arguments, or passing an argument that it is not
specified to handle.

The \var{who} argument should describe the procedure or operation that
detected the exception.  The \var{message} argument should describe
the exceptional situation.  The \var{irritant}s should be the arguments
to the operation that detected the operation.

The condition object provided with the exception (see
library chapter~\extref{lib:exceptionsconditionschapter}{Exceptions
  and conditions}) has the following condition types:
%
\begin{itemize}
\item If \var{who} is not \schfalse, the condition has condition type
  {\cf \&who}, with \var{who} as the value of its field.  In
  that case, \var{who} should be the name of the procedure or entity that
  detected the exception.  If it is \schfalse, the condition does not
  have condition type {\cf \&who}.
\item The condition has condition type {\cf \&message}, with
  \var{message} as the value of its field.
\item The condition has condition type {\cf \&irritants}, and its
  field has as its value a list of the \var{irritant}s.
\end{itemize}
%
Moreover, the condition created by {\cf error} has condition type
{\cf \&error}, and the condition created by {\cf assertion-\hp{}violation} has
condition type {\cf \&assertion}.

\begin{scheme}
(define (fac n)
  (if (not (integer-valued? n))
      (assertion-violation
       'fac "non-integral argument" n))
  (if (negative? n)
      (assertion-violation
       'fac "negative argument" n))
  (letrec
    ((loop (lambda (n r)
             (if (zero? n)
                 r
                 (loop (- n 1) (* r n))))))
      (loop n 1)))

(fac 5) \ev 120
(fac 4.5) \xev \exception{\&assertion}
(fac -3) \xev \exception{\&assertion}%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{assert}{ \hyper{expression}}{\exprtype}}

An {\cf assert} form is evaluated by evaluating \hyper{expression}.
If \hyper{expression} returns a true value, that value is returned
from the {\cf assert} expression.  If \hyper{expression} returns
\schfalse, an exception with condition types {\cf \&assertion} and
{\cf \&message} is raised.  The message provided in the condition
object is implementation-dependent.

\begin{note}
  Implementations should exploit the fact that
  {\cf assert} is syntax to provide as much information as possible
  about the location of the assertion failure.
\end{note}
\end{entry}

\section{Control features}
\label{controlsection}
\label{valuessection}

This chapter describes various primitive procedures which control the
flow of program execution in special ways.

\begin{entry}{%
\proto{apply}{ proc \vari{arg} $\ldots$ rest-args}{procedure}}

\domain{\var{Rest-args} must be a list.
 \var{Proc} should accept $n$ arguments, where $n$ is
  number of \var{arg}s plus the length of \var{rest-args}.}
The {\cf apply} procedure calls \var{proc} with the elements of the list
{\cf(append (list \vari{arg} \dotsfoo) \var{rest-args})} as the actual
arguments.

If a call to {\cf apply} occurs in a tail context, the call
to \var{proc} is also in a tail context.

\begin{scheme}
(apply + (list 3 4))              \ev  7

(define compose
  (lambda (f g)
    (lambda args
      (f (apply g args)))))

((compose sqrt *) 12 75)              \ev  30%
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{call-with-current-continuation}{ proc}{procedure}
\proto{call/cc}{ proc}{procedure}}

\label{continuations} \domain{\var{Proc} should accept one
argument.} The procedure {\cf call-with-current-continuation}
(which is the same as the procedure {\cf call/cc}) packages
the current continuation as an ``escape
procedure''\mainindex{escape procedure} and passes it as an argument to
\var{proc}.  The escape procedure is a Scheme procedure that, if it is
later called, will abandon whatever continuation is in effect at that later
time and will instead reinstate the continuation that was in effect
when the escape procedure was created.  Calling the escape procedure
may cause the invocation of \var{before} and \var{after} procedures installed using
\ide{dynamic-wind}.

The escape procedure accepts the same number of arguments as the
continuation of the original call to {\cf call-\hp{}with-\hp{}current-\hp{}continuation}.

The escape procedure that is passed to \var{proc} has
unlimited extent just like any other procedure in Scheme.  It may be stored
in variables or data structures and may be called as many times as desired.

If a call to {\cf call-with-current-continuation} occurs in a tail
context, the call to \var{proc} is also in a tail context.

The following examples show only some ways in which
{\cf call-with-current-continuation} is used.  If all real uses were as
simple as these examples, there would be no need for a procedure with
the power of {\cf call-\hp{}with-\hp{}current-\hp{}continuation}.

\begin{scheme}
(call-with-current-continuation
  (lambda (exit)
    (for-each (lambda (x)
                (if (negative? x)
                    (exit x)))
              '(54 0 37 -3 245 19))
    \schtrue))                        \ev  -3

(define list-length
  (lambda (obj)
    (call-with-current-continuation
      (lambda (return)
        (letrec ((r
                  (lambda (obj)
                    (cond ((null? obj) 0)
                          ((pair? obj)
                           (+ (r (cdr obj)) 1))
                          (else (return \schfalse))))))
          (r obj))))))

(list-length '(1 2 3 4))            \ev  4

(list-length '(a b . c))            \ev  \schfalse%

(call-with-current-continuation procedure?)
                            \ev  \schtrue%
\end{scheme}

\begin{note}
  Calling an escape procedure reenters the dynamic extent of the call
  to {\cf call-with-current-continuation}, and thus restores its
  dynamic environment; see section~\ref{dynamicenvironmentsection}.
\end{note}

\end{entry}

\begin{entry}{%
\proto{values}{ obj $\ldots$}{procedure}}

Delivers all of its arguments to its continuation.
The {\cf values} procedure might be defined as follows:
\begin{scheme}
(define (values . things)
  (call-with-current-continuation
    (lambda (cont) (apply cont things))))%
\end{scheme}

The continuations of all non-final expressions within a sequence of
expressions, such as in {\cf lambda}, {\cf begin}, {\cf let}, {\cf
  let*}, {\cf letrec}, {\cf letrec*}, {\cf let-values}, {\cf
  let*-values}, {\cf case}, and {\cf cond} forms, usually take an
arbitrary number of values.

Except for these and the continuations created by {\cf
  call-\hp{}with-\hp{}values}, {\cf let-values}, and {\cf let*-values},
continuations implicitly accepting a single value, such as the
continuations of \hyper{operator} and \hyper{operand}s of procedure
calls or the \hyper{test} expressions in conditionals, take exactly
one value.  The effect of passing an inappropriate number of values to
such a continuation is undefined.
\end{entry}

\begin{entry}{%
\proto{call-with-values}{ producer consumer}{procedure}}

\domain{\var{Producer} must be a procedure and should accept zero
  arguments.  \var{Consumer} must be a procedure and should accept as many
  values as \var{producer} returns.}
The {\cf call-\hp{}with-\hp{}values} procedure calls \var{producer} with no arguments and
a continuation that, when passed some values, calls the
\var{consumer} procedure with those values as arguments.
The continuation for the call to \var{consumer} is the
continuation of the call to {\tt call-with-values}.

\begin{scheme}
(call-with-values (lambda () (values 4 5))
                  (lambda (a b) b))
                                                   \ev  5

(call-with-values * -)                             \ev  -1%
\end{scheme}

If a call to {\cf call-with-values} occurs in a tail context, the call
to \var{consumer} is also in a tail context.

\implresp After \var{producer} returns, the implementation must check
that \var{consumer} accepts as many values as \var{consumer} has
returned.
\end{entry}

\begin{entry}{%
\proto{dynamic-wind}{ before thunk after}{procedure}}

\domain{\var{Before}, \var{thunk}, and \var{after} must be procedures,
  and each should accept zero arguments.  These procedures may return
  any number of values.}  The {\cf dynamic-wind} procedure calls
\var{thunk} without arguments, returning the results of this call.
Moreover, {\cf dynamic-wind} calls \var{before} without arguments
whenever the dynamic extent of the call to \var{thunk} is entered, and
\var{after} without arguments whenever the dynamic extent of the call
to \var{thunk} is exited.  Thus, in the absence of calls to escape
procedures created by {\cf call-with-current-continuation}, {\cf
  dynamic-wind} calls \var{before}, \var{thunk}, and \var{after}, in
that order.

While the calls to \var{before} and \var{after} are not considered to be
within the dynamic extent of the call to \var{thunk}, calls to the \var{before}
and \var{after} procedures of any other calls to {\cf dynamic-wind} that occur
within the dynamic extent of the call to \var{thunk} are considered to be
within the dynamic extent of the call to \var{thunk}.

More precisely, an escape procedure transfers control out of the
dynamic extent of a set of zero or more active {\cf dynamic-wind}
calls $x\ \dots$ and transfer control into the dynamic extent
of a set of zero or more active {\cf dynamic-wind} calls
$y\ \dots$.
It leaves the dynamic extent of the most recent $x$ and calls without
arguments the corresponding \var{after} procedure.
If the \var{after} procedure returns, the escape procedure proceeds to
the next most recent $x$, and so on.
Once each $x$ has been handled in this manner,
the escape procedure calls without arguments the \var{before} procedure
corresponding to the least recent $y$.
If the \var{before} procedure returns, the escape procedure reenters the
dynamic extent of the least recent $y$ and proceeds with the next least
recent $y$, and so on.
Once each $y$ has been handled in this manner, control is transferred to
the continuation packaged in the escape procedure.

\implresp The implementation must check the restrictions on
\var{thunk} and \var{after} only if they are actually called.

\begin{scheme}
(let ((path '())
      (c \#f))
  (let ((add (lambda (s)
               (set! path (cons s path)))))
    (dynamic-wind
      (lambda () (add 'connect))
      (lambda ()
        (add (call-with-current-continuation
               (lambda (c0)
                 (set! c c0)
                 'talk1))))
      (lambda () (add 'disconnect)))
    (if (< (length path) 4)
        (c 'talk2)
        (reverse path))))
    \lev (connect talk1 disconnect
               connect talk2 disconnect)

(let ((n 0))
  (call-with-current-continuation
    (lambda (k)
      (dynamic-wind
        (lambda ()
          (set! n (+ n 1))
          (k))
        (lambda ()
          (set! n (+ n 2)))
        (lambda ()
          (set! n (+ n 4))))))
  n) \ev 1

(let ((n 0))
  (call-with-current-continuation
    (lambda (k)
      (dynamic-wind
        values
        (lambda ()
          (dynamic-wind
            values
            (lambda ()
              (set! n (+ n 1))
              (k))
            (lambda ()
              (set! n (+ n 2))
              (k))))
        (lambda ()
          (set! n (+ n 4))))))
  n) \ev 7%
\end{scheme}

\begin{note}
  Entering a dynamic extent restores its dynamic environment; see
  section~\ref{dynamicenvironmentsection}.
\end{note}
\end{entry}

\section{Iteration}\unsection

\begin{entry}{%
\rproto{let}{ \hyper{variable} \hyper{bindings} \hyper{body}}{\exprtype}}

\label{namedlet}
``Named {\cf let}'' is a variant on the syntax of \ide{let} that provides
a general looping construct and may also be used to express
recursion.
It has the same syntax and semantics as ordinary {\cf let}
except that \hyper{variable} is bound within \hyper{body} to a procedure
whose parameters are the bound variables and whose body is
\hyper{body}.  Thus the execution of \hyper{body} may be repeated by
invoking the procedure named by \hyper{variable}.

%                                              |  <-- right margin
\begin{scheme}
(let loop ((numbers '(3 -2 1 6 -5))
           (nonneg '())
           (neg '()))
  (cond ((null? numbers) (list nonneg neg))
        ((>= (car numbers) 0)
         (loop (cdr numbers)
               (cons (car numbers) nonneg)
               neg))
        ((< (car numbers) 0)
         (loop (cdr numbers)
               nonneg
               (cons (car numbers) neg))))) %
  \lev  ((6 1 3) (-5 -2))%
\end{scheme}

\end{entry}

\section{Quasiquotation}\unsection
\label{quasiquotesection}

\begin{entry}{%
\proto{quasiquote}{ \hyper{qq template}}{\exprtype}
\litproto{unquote}
\litproto{unquote-splicing}}

``Backquote'' or ``quasiquote''\index{backquote} expressions are useful
for constructing a list or vector structure when some but not all of the
desired structure is known in advance.

\syntax \hyper{Qq template} should be as specified by the grammar at
the end of this entry.

\semantics If no
{\cf unquote} or {\cf unquote-splicing} forms
appear within the \hyper{qq template}, the result of
evaluating
{\cf (quasiquote \hyper{qq template})} is equivalent to the result of evaluating
{\cf (quote \hyper{qq template})}.

If an {\cf (unquote \hyper{expression} \dotsfoo)} form appears inside a
\hyper{qq template}, however, the \hyper{expression}s are evaluated
(``unquoted'') and their results are inserted into the structure instead
of the {\cf unquote} form.

If an {\cf (unquote-splicing \hyper{expression} \dotsfoo)} form
appears inside a \hyper{qq template}, then the \hyper{expression}s must
evaluate to lists; the opening and closing parentheses of the lists are
then ``stripped away'' and the elements of the lists are inserted in
place of the {\cf unquote-splicing} form.

Any {\cf unquote-splicing} or multi-operand {\cf unquote} form must
appear only within a list or vector \hyper{qq template}.

As noted in section~\ref{abbreviationsection},
{\cf (quasiquote \hyper{qq template})} may be abbreviated
\backquote\hyper{qq template},
{\cf (unquote \hyper{expression})} may be abbreviated
{\cf,}\hyper{expression}, and
{\cf (unquote-splicing \hyper{expression})} may be abbreviated
{\cf,}\atsign\hyper{expression}.

\begin{scheme}
`(list ,(+ 1 2) 4)  \ev  (list 3 4)
(let ((name 'a)) `(list ,name ',name)) %
          \lev  (list a (quote a))
`(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b) %
          \lev  (a 3 4 5 6 b)
`(({\cf foo} ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))) %
          \lev  ((foo 7) . cons)
`\#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8) %
          \lev  \#(10 5 2 4 3 8)
(let ((name 'foo))
  `((unquote name name name)))%
          \lev (foo foo foo)
(let ((name '(foo)))
  `((unquote-splicing name name name)))%
          \lev (foo foo foo)
(let ((q '((append x y) (sqrt 9))))
  ``(foo ,,@q)) \lev `(foo
                 (unquote (append x y) (sqrt 9)))
(let ((x '(2 3))
      (y '(4 5)))
  `(foo (unquote (append x y) (sqrt 9)))) \lev (foo (2 3 4 5) 3)%
\end{scheme}

Quasiquote forms may be nested.  Substitutions are made only for
unquoted components appearing at the same nesting level
as the outermost {\cf quasiquote}.  The nesting level increases by one inside
each successive quasiquotation, and decreases by one inside each
unquotation.

\begin{scheme}
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) %
          \lev  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
(let ((name1 'x)
      (name2 'y))
  `(a `(b ,,name1 ,',name2 d) e)) %
          \lev  (a `(b ,x ,'y d) e)%
\end{scheme}

A {\cf quasiquote} expression may return either fresh, mutable objects
or literal structure for any structure that is constructed at run time
during the evaluation of the expression.  Portions that do not need to
be rebuilt are always literal.  Thus,
%
\begin{scheme}
(let ((a 3)) `((1 2) ,a ,4 ,'five 6))%
\end{scheme}
%
may be equivalent to either of the following expressions:
%
\begin{scheme}
'((1 2) 3 4 five 6)
(let ((a 3))
  (cons '(1 2)
        (cons a (cons 4 (cons 'five '(6))))))%
\end{scheme}
%
However, it is not equivalent to this expression:
%
\begin{scheme}
(let ((a 3)) (list (list 1 2) a 4 'five 6))
\end{scheme}
%
It is a syntax violation if any of the identifiers
\ide{quasiquote}, \ide{unquote}, or \ide{unquote-splicing} appear in
positions within a \hyper{qq template} otherwise than as described above.

The following grammar for quasiquote expressions is not context-free.
It is presented as a recipe for generating an infinite number of
production rules.  Imagine a copy of the following rules for $D = 1, 2,
3, \ldots$.  $D$ keeps track of the nesting depth.

\begin{grammar}%
\meta{qq template} \: \meta{qq template 1}
\meta{qq template 0} \: \meta{expression}
\meta{quasiquotation $D$} \: (quasiquote \meta{qq template $D$})
\meta{qq template $D$} \: \meta{lexeme datum}
\>    \| \meta{list qq template $D$}
\>    \| \meta{vector qq template $D$}
\>    \| \meta{unquotation $D$}
\meta{list qq template $D$} \: (\arbno{\meta{qq template or splice $D$}})
\>    \| (\atleastone{\meta{qq template or splice $D$}} .\ \meta{qq template $D$})
\>    \| \meta{quasiquotation $D+1$}
\meta{vector qq template $D$} \: \#(\arbno{\meta{qq template or splice $D$}})
\meta{unquotation $D$} \: (unquote \meta{qq template $D-1$})
\meta{qq template or splice $D$} \: \meta{qq template $D$}
\>    \| \meta{splicing unquotation $D$}
\meta{splicing unquotation $D$} \:
\>\> (unquote-splicing \arbno{\meta{qq template $D-1$}})
\>    \| (unquote \arbno{\meta{qq template $D-1$}}) %
\end{grammar}

In \meta{quasiquotation}s, a \meta{list qq template $D$} can sometimes
be confused with either an \meta{un\-quota\-tion $D$} or a \meta{splicing
un\-quo\-ta\-tion $D$}.  The interpretation as an
\meta{un\-quo\-ta\-tion} or \meta{splicing
un\-quo\-ta\-tion $D$} takes precedence.

\end{entry}

\section{Binding constructs for syntactic keywords}
\label{bindsyntax}

The {\cf let-syntax} and {\cf letrec-syntax} forms
bind keywords.
Like a {\cf begin} form, a {\cf let-syntax} or {\cf letrec-syntax} form
may appear in a definition context, in which case it is treated as a
definition, and the forms in the body must also be
definitions.
A {\cf let-syntax} or {\cf letrec-syntax} form may also appear in an
expression context, in which case the forms within their bodies must be
expressions.

\begin{entry}{%
\proto{let-syntax}{ \hyper{bindings} \hyper{form} \dotsfoo}{\exprtype}}

\syntax
\hyper{Bindings} must have the form
\begin{scheme}
((\hyper{keyword} \hyper{expression}) \dotsfoo)%
\end{scheme}
Each \hyper{keyword} is an identifier,
and each \hyper{expression} is
an expression that evaluates, at macro-expansion
time, to a \textit{transformer}\index{transformer}\index{macro transformer}.
Transformers may be created by {\cf syntax-rules} or {\cf identifier-syntax}
(see section~\ref{syntaxrulessection}) or by one of the other mechanisms
described in library chapter~\extref{lib:syntaxcasechapter}{{\cf syntax-case}}.  It is a
syntax violation for \hyper{keyword} to appear more than once in the list of keywords
being bound.

\semantics
The \hyper{form}s are expanded in the syntactic environment
obtained by extending the syntactic environment of the
{\cf let-syntax} form with macros whose keywords are
the \hyper{keyword}s, bound to the specified transformers.
Each binding of a \hyper{keyword} has the \hyper{form}s as its region.

The \hyper{form}s of a {\cf let-syntax}
form are treated, whether in definition or expression context, as if
wrapped in an implicit {\cf begin}; see section~\ref{begin}.
Thus definitions in the result of expanding the \hyper{form}s have
the same region as any definition appearing in place of the {\cf
  let-syntax} form would have.

\implresp The implementation should detect if the value of
\hyper{expression} cannot possibly be a transformer.

\begin{scheme}
(let-syntax ((when (syntax-rules ()
                     ((when test stmt1 stmt2 ...)
                      (if test
                          (begin stmt1
                                 stmt2 ...))))))
  (let ((if \schtrue))
    (when if (set! if 'now))
    if))                           \ev  now

(let ((x 'outer))
  (let-syntax ((m (syntax-rules () ((m) x))))
    (let ((x 'inner))
      (m))))                       \ev  outer%

(let ()
  (let-syntax
    ((def (syntax-rules ()
            ((def stuff ...) (define stuff ...)))))
    (def foo 42))
  foo) \ev 42

(let ()
  (let-syntax ())
  5) \ev 5%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{letrec-syntax}{ \hyper{bindings} \hyper{form} \dotsfoo}{\exprtype}}

\syntax
Same as for {\cf let-syntax}.

\semantics
The \hyper{form}s are
expanded in the syntactic environment obtained by
extending the syntactic environment of the {\cf letrec-syntax}
form with macros whose keywords are the
\hyper{keyword}s, bound to the specified transformers.
Each binding of a \hyper{keyword} has the \hyper{bindings}
as well as the \hyper{form}s within its region,
so the transformers can
transcribe forms into uses of the macros
introduced by the {\cf letrec-syntax} form.

The \hyper{form}s of a {\cf letrec-syntax}
form are treated, whether in definition or expression context, as if
wrapped in an implicit {\cf begin}; see section~\ref{begin}.
Thus definitions in the result of expanding the \hyper{form}s have
the same region as any definition appearing in place of the {\cf
  letrec-syntax} form would have.

\implresp The implementation should detect if the value of
\hyper{expression} cannot possibly be a transformer.

\begin{scheme}
(letrec-syntax
  ((my-or (syntax-rules ()
            ((my-or) \schfalse)
            ((my-or e) e)
            ((my-or e1 e2 ...)
             (let ((temp e1))
               (if temp
                   temp
                   (my-or e2 ...)))))))
  (let ((x \schfalse)
        (y 7)
        (temp 8)
        (let odd?)
        (if even?))
    (my-or x
           (let temp)
           (if y)
           y)))        \ev  7%
\end{scheme}

The following example highlights how {\cf let-syntax}
and {\cf letrec-syntax} differ.

\begin{scheme}
(let ((f (lambda (x) (+ x 1))))
  (let-syntax ((f (syntax-rules ()
                    ((f x) x)))
               (g (syntax-rules ()
                    ((g x) (f x)))))
    (list (f 1) (g 1)))) \lev (1 2)

(let ((f (lambda (x) (+ x 1))))
  (letrec-syntax ((f (syntax-rules ()
                       ((f x) x)))
                  (g (syntax-rules ()
                       ((g x) (f x)))))
    (list (f 1) (g 1)))) \lev (1 1)%
\end{scheme}

The two expressions are identical except that the {\cf let-syntax} form
in the first expression is a {\cf letrec-syntax} form in the second.
In the first expression, the {\cf f} occurring in {\cf g} refers to
the {\cf let}-bound variable {\cf f}, whereas in the second it refers
to the keyword {\cf f} whose binding is established by the
{\cf letrec-syntax} form.
\end{entry}

\section{Macro transformers}
\label{syntaxrulessection}

\begin{entry}{%
\pproto{(syntax-rules (\hyper{literal} \dotsfoo) \hyper{syntax rule} \dotsfoo)}{\exprtype~({\cf expand})}
\litprotoexpandnoindex{\_}
\litprotoexpand{...}}
\mainschindex{syntax-rules}\schindex{\_}

\syntax Each \hyper{literal} must be an identifier.
Each \hyper{syntax rule} must have the following form:

\begin{scheme}
(\hyper{srpattern} \hyper{template})%
\end{scheme}

An \hyper{srpattern} is a restricted form of \hyper{pattern},
namely, a nonempty \hyper{pattern} in one of four parenthesized forms below
whose first subform is an identifier or an underscore {\cf \_}\schindex{\_}.
A \hyper{pattern} is an identifier, constant, or one of the following.

\begin{schemenoindent}
(\hyper{pattern} \ldots)
(\hyper{pattern} \hyper{pattern} \ldots . \hyper{pattern})
(\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis} \hyper{pattern} \ldots)
(\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis} \hyper{pattern} \ldots . \hyper{pattern})
\#(\hyper{pattern} \ldots)
\#(\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis} \hyper{pattern} \ldots)%
\end{schemenoindent}

An \hyper{ellipsis} is the identifier ``{\cf ...}'' (three periods).\schindex{...}

A \hyper{template} is a pattern variable, an identifier that
is not a pattern
variable, a pattern datum, or one of the following.

\begin{scheme}
(\hyper{subtemplate} \ldots)
(\hyper{subtemplate} \ldots . \hyper{template})
\#(\hyper{subtemplate} \ldots)%
\end{scheme}

A \hyper{subtemplate} is a \hyper{template} followed by zero or more ellipses.

\semantics An instance of {\cf syntax-rules} evaluates, at
macro-expansion time, to a new macro
transformer by specifying a sequence of hygienic rewrite rules.  A use
of a macro whose keyword is associated with a transformer specified by
{\cf syntax-rules} is matched against the patterns contained in the
\hyper{syntax rule}s, beginning with the leftmost \hyper{syntax rule}.
When a match is found, the macro use is transcribed hygienically
according to the template.  It is a syntax violation when no match is found.

An identifier appearing within a \hyper{pattern} may be an underscore
(~{\cf \_}~), a literal identifier listed in the list of literals
{\cf (\hyper{literal} \dotsfoo)}, or an ellipsis (~{\cf ...}~).
All other identifiers appearing within a \hyper{pattern} are
\textit{pattern variables\mainindex{pattern variable}}.
It is a syntax violation if an ellipsis or underscore appears in {\cf (\hyper{literal} \dotsfoo)}.

While the first subform of \hyper{srpattern} may be an identifier, the
identifier is not involved in the matching and
is not considered a pattern variable or literal identifier.

Pattern variables match arbitrary input subforms and
are used to refer to elements of the input.
It is a syntax violation if the same pattern variable appears more than once in a
\hyper{pattern}.

Underscores also match arbitrary input subforms but are not pattern variables
and so cannot be used to refer to those elements.
Multiple underscores may appear in a \hyper{pattern}.

A literal identifier matches an input subform if and only if the input
subform is an identifier and either both its occurrence in the input
expression and its occurrence in the list of literals have the same
lexical binding, or the two identifiers have the same name and both have
no lexical binding.

A subpattern followed by an ellipsis can match zero or more elements of
the input.

More formally, an input form $F$ matches a pattern $P$ if and only if
one of the following holds:

\begin{itemize}
\item $P$ is an underscore (~{\cf \_}~).

\item $P$ is a pattern variable.

\item $P$ is a literal identifier
and $F$ is an identifier such that both $P$ and $F$ would refer to the
same binding if both were to appear in the output of the macro outside
of any bindings inserted into the output of the macro.
(If neither of two like-named identifiers refers to any binding, i.e., both
are undefined, they are considered to refer to the same binding.)

\item $P$ is of the form
{\cf ($P_1$ \dotsfoo{} $P_n$)}
and $F$ is a list of $n$ elements that match $P_1$ through
$P_n$.

\item $P$ is of the form
{\cf ($P_1$ \dotsfoo{} $P_n$ . $P_x$)}
and $F$ is a list or improper list of $n$ or more elements
whose first $n$ elements match $P_1$ through $P_n$
and
whose $n$th cdr matches $P_x$.

\item $P$ is of the form
{\cf ($P_1$ \dotsfoo{} $P_k$ $P_e$ \hyper{ellipsis} $P_{m+1}$ \dotsfoo{} $P_n$)},
where \hyper{ellipsis} is the identifier {\cf ...}
and $F$ is a list of $n$
elements whose first $k$ elements match $P_1$ through $P_k$,
whose next $m-k$ elements each match $P_e$,
and
whose remaining $n-m$ elements match $P_{m+1}$ through $P_n$.

\item $P$ is of the form
{\cf ($P_1$ \dotsfoo{} $P_k$ $P_e$ \hyper{ellipsis} $P_{m+1}$ \dotsfoo{} $P_n$ . $P_x$)},
where \hyper{ellipsis} is the identifier {\cf ...}
and $F$ is a list or improper list of $n$
elements whose first $k$ elements match $P_1$ through $P_k$,
whose next $m-k$ elements each match $P_e$,
whose next $n-m$ elements match $P_{m+1}$ through $P_n$,
and
whose $n$th and final cdr matches $P_x$.

\item $P$ is of the form
{\cf \#($P_1$ \dotsfoo{} $P_n$)}
and $F$ is a vector of $n$ elements that match $P_1$ through
$P_n$.

\item $P$ is of the form
{\cf \#($P_1$ \dotsfoo{} $P_k$ $P_e$ \hyper{ellipsis} $P_{m+1}$ \dotsfoo{} $P_n$)},
where \hyper{ellipsis} is the identifier {\cf ...}
and $F$ is a vector of $n$ or more elements
whose first $k$ elements match $P_1$ through $P_k$,
whose next $m-k$ elements each match $P_e$,
and
whose remaining $n-m$ elements match $P_{m+1}$ through $P_n$.

\item $P$ is a pattern datum (any nonlist, nonvector, nonsymbol
datum) and $F$ is equal to $P$ in the sense of the
{\cf equal?} procedure.
\end{itemize}

When a macro use is transcribed according to the template of the
matching \hyper{syntax rule}, pattern variables that occur in the
template are replaced by the subforms they match in the input.

Pattern data and identifiers that are not pattern variables
or ellipses are copied into the output.
A subtemplate followed by an ellipsis expands
into zero or more occurrences of the subtemplate.
Pattern variables that occur in subpatterns followed by one or more
ellipses may occur only in subtemplates that are
followed by (at least) as many ellipses.
These pattern variables are replaced in the output by the input
subforms to which they are bound, distributed as specified.
If a pattern variable is followed by more ellipses in the subtemplate
than in the associated subpattern, the input form is replicated as
necessary.
The subtemplate must contain at least one pattern variable from a
subpattern followed by an ellipsis, and for at least one such pattern
variable, the subtemplate must be followed by exactly as many ellipses as
the subpattern in which the pattern variable appears.
(Otherwise, the expander would not be able to determine how many times the
subform should be repeated in the output.)
It is a syntax violation if the constraints of this paragraph are not met.

A template of the form
{\cf (\hyper{ellipsis} \hyper{template})} is identical to \hyper{template}, except that
ellipses within the template have no special meaning.
That is, any ellipses contained within \hyper{template} are
treated as ordinary identifiers.
In particular, the template {\cf (... ...)} produces a single
ellipsis, {\cf ...}.
This allows syntactic abstractions to expand into forms containing
ellipses.

\begin{scheme}
(define-syntax be-like-begin
  (syntax-rules ()
    ((be-like-begin name)
     (define-syntax name
       (syntax-rules ()
         ((name expr (... ...))
          (begin expr (... ...))))))))

(be-like-begin sequence)
(sequence 1 2 3 4) \ev 4%
\end{scheme}

As an example for hygienic use of auxiliary identifier,
if \ide{let} and \ide{cond} are defined as in
section~\ref{let} and appendix~\ref{derivedformsappendix} then they
are hygienic (as required) and the following is not an error.

\begin{scheme}
(let ((=> \schfalse))
  (cond (\schtrue => 'ok)))           \ev ok%
\end{scheme}

The macro transformer for {\cf cond} recognizes {\cf =>}
as a local variable, and hence an expression, and not as the
identifier {\cf =>}, which the macro transformer treats
as a syntactic keyword.  Thus the example expands into

\begin{scheme}
(let ((=> \schfalse))
  (if \schtrue (begin => 'ok)))%
\end{scheme}

instead of

\begin{scheme}
(let ((=> \schfalse))
  (let ((temp \schtrue))
    (if temp ('ok temp))))%
\end{scheme}

which would result in an assertion violation.
\end{entry}

\begin{entry}{%
\proto{identifier-syntax}{ \hyper{template}}{\exprtype~({\cf expand})}
\pproto{(identifier-syntax}{\exprtype~({\cf expand})}}\\
{\tt\obeyspaces
  (\hyperi{id} \hyperi{template})\\
  ((set! \hyperii{id} \hyper{pattern})\\
   \hyperii{template}))\\
\litprotoexpandnoindex{set!}}

\syntax The \hyper{id}s must be identifiers.  The \hyper{template}s
must be as for {\cf syntax-rules}.

\semantics
When a keyword is bound to a transformer produced by the first form of
{\cf identifier-syntax}, references to the keyword within the scope
of the binding are replaced by \hyper{template}.

\begin{scheme}
(define p (cons 4 5))
(define-syntax p.car (identifier-syntax (car p)))
p.car \ev 4
(set! p.car 15) \ev \exception{\&syntax}%
\end{scheme}

The second, more general, form of {\cf identifier-syntax} permits
the transformer to determine what happens when {\cf set!} is used.
In this case, uses of the identifier by itself are replaced by
\hyperi{template}, and uses of {\cf set!} with the identifier are
replaced by \hyperii{template}.

\begin{scheme}
(define p (cons 4 5))
(define-syntax p.car
  (identifier-syntax
    (\_ (car p))
    ((set! \_ e) (set-car! p e))))
(set! p.car 15)
p.car           \ev 15
p               \ev (15 5)%
\end{scheme}

\end{entry}

\section{Tail calls and tail contexts}
\label{basetailcontextsection}

A {\em tail call}\mainindex{tail call} is a procedure call that occurs
in a {\em tail context}.  Tail contexts are defined inductively.  Note
that a tail context is always determined with respect to a particular lambda
expression.

\begin{itemize}
\item The last expression within the body of a lambda expression,
  shown as \hyper{tail expression} below, occurs in a tail context.
%
\begin{scheme}
(l\=ambda \hyper{formals}
  \>\arbno{\hyper{definition}}
  \>\arbno{\hyper{expression}} \hyper{tail expression})%
\end{scheme}
%
\item If one of the following expressions is in a tail context,
then the subexpressions shown as \hyper{tail expression} are in a tail context.
These were derived from specifications of the syntax of the forms described in
this chapter by replacing some occurrences of \hyper{expression}
with \hyper{tail expression}.  Only those rules that contain tail contexts
are shown here.
%
\begin{scheme}
(if \hyper{expression} \hyper{tail expression} \hyper{tail expression})
(if \hyper{expression} \hyper{tail expression})

(cond \atleastone{\hyper{cond clause}})
(cond \arbno{\hyper{cond clause}} (else \hyper{tail sequence}))

(c\=ase \hyper{expression}
  \>\atleastone{\hyper{case clause}})
(c\=ase \hyper{expression}
  \>\arbno{\hyper{case clause}}
  \>(else \hyper{tail sequence}))

(and \arbno{\hyper{expression}} \hyper{tail expression})
(or \arbno{\hyper{expression}} \hyper{tail expression})

(let \hyper{bindings} \hyper{tail body})
(let \hyper{variable} \hyper{bindings} \hyper{tail body})
(let* \hyper{bindings} \hyper{tail body})
(letrec* \hyper{bindings} \hyper{tail body})
(letrec \hyper{bindings} \hyper{tail body})
(let-values \hyper{mv-bindings} \hyper{tail body})
(let*-values \hyper{mv-bindings} \hyper{tail body})

(let-syntax \hyper{bindings} \hyper{tail body})
(letrec-syntax \hyper{bindings} \hyper{tail body})

(begin \hyper{tail sequence})%
\end{scheme}
%
A \hyper{cond clause} is
%
\begin{scheme}
(\hyper{test} \hyper{tail sequence})\textrm{,}%
\end{scheme}
a \hyper{case clause} is
%
\begin{scheme}
((\arbno{\hyper{datum}}) \hyper{tail sequence})\textrm{,}%
\end{scheme}
%
a \hyper{tail body} is
\begin{scheme}
\arbno{\hyper{definition}} \hyper{tail sequence}\textrm{,}%
\end{scheme}
%
and a \hyper{tail sequence} is
%
\begin{scheme}
\arbno{\hyper{expression}} \hyper{tail expression}\textrm{.}%
\end{scheme}%

\item
If a {\cf cond} expression is in a tail context, and has a clause of
the form {\cf (\hyperi{expression} => \hyperii{expression})}
then the (implied) call to
the procedure that results from the evaluation of \hyperii{expression} is in a
tail context.  \hyperii{Expression} itself is not in a tail context.

\end{itemize}

Certain built-in procedures must also perform tail calls.
The first argument passed to {\cf apply} and to
{\cf call-\hp{}with-\hp{}current-continuation}, and the second argument passed to
{\cf call-with-values}, must be called via a tail call.

In the following example the only tail call is the call to {\cf f}.
None of the calls to {\cf g} or {\cf h} are tail calls.  The reference to
{\cf x} is in a tail context, but it is not a call and thus is not a
tail call.
\begin{scheme}%
(lambda ()
  (if (g)
      (let ((x (h)))
        x)
      (and (g) (f))))%
\end{scheme}%

\begin{note}
Implementations may
recognize that some non-tail calls, such as the call to {\cf h}
above, can be evaluated as though they were tail calls.
In the example above, the {\cf let} expression could be compiled
as a tail call to {\cf h}. (The possibility of {\cf h} returning
an unexpected number of values can be ignored, because in that
case the effect of the {\cf let} is explicitly unspecified and
implementation-dependent.)
\end{note}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "r6rs"
%%% End:
